私はノードjsを初めて使っています。私はforループを使用して、同じ関数を異なる値で複数回起動します。私はまた、ウェブサイトからデータをスクラップするリクエストを使用しています。しかし、すべてのプロセスを完了すれば、スクリプトは自動的に終了しません。要求接続が閉じられていないなど、多くの理由があります。非同期的に実行されているため、手動で閉じることはできません。 process.exit()を使用している場合。 forループの最後の行では、関数を実行する直前に閉じられます。 forループが完了したら、このスクリプトをどのように終了させるのですか?私を助けてください。すべてのプロセスが完了したらノードjsスクリプトを終了する方法
私の作業コードは次のとおりです。
const request = require('request');
const cheerio = require('cheerio');
const Sequelize = require('sequelize');
var redis = require("redis"),
client = redis.createClient();
var id = [20434, 21794, 21825, 21350, 20753, 20451];
const sequelize = new Sequelize('xyz', 'root', 'root', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 90000,
acquire: 90000
},
});
const User = sequelize.define('abcd', {
'X': {
type: Sequelize.STRING
},
'Y': {
type: Sequelize.STRING
},
'A': {
type: Sequelize.INTEGER
},
'abc': {
type: Sequelize.STRING
},
'info': {
type: Sequelize.STRING
},
},{
tableName: 'xyz'
});
for(var x=0; x<id.length; x++){
scrapeweb(id[x], x);
}
function scrapeweb(id, text, done){
try {
switch(text) {
case 0:
lang = "english";
break;
case 1:
lang = "hindi";
break;
case 2:
lang = "tamil";
break;
case 3:
lang = "malayalam";
break;
case 4:
lang = "kannada";
break;
case 5:
lang = "telugu";
break;
default:
lang = "language"
break;
}
request("http://www*xyz*com/jfkdh/"+id+"/", function(error, response, body) {
if(error) {
console.log(error);
var err = new Error('Exception in requesting url')
throw err
}
//scrap the given url and get song-names
.....
.....
.....
.....
for(var i=0; i<text.length; i++){
//DB section to check the song is available or not.
User.findOne({attributes: ['A', 'B'],
where: {
B: { $like: '%'+word[i]+'%'} ,
X: "....."
}
}).then(data => {
if(data != null) {
//Redis section
client.on("error", function (err) {
console.log(err);
var err = new Error('Exception in redis client connection')
throw err
});
if(client.hexists('word', data.dataValues['A']) == true) {
client.hincrby('word', data.dataValues['A'] , 1);
} else {
// client.hincrby('word', 'count', 1);
client.hmset('word', data.dataValues['A'], 0);
client.expire('word', 86400);
}
console.log(data.dataValues['B']+" is available and language = "+lang);
} else {
console.log("word is not avilable");
}
});
}
});
});
} catch(err) {
console.log(err);
}
}
あなたが試したコードを投稿してください。 – Subburaj
は自分のコードを追加しました。今すぐチェックしてください –
'' 'request-promise'''(https://github.com/request/request-promise)を使い、すべてのリクエストを' 'Promise.all'''に入れてください。それらが完了したら '' '.then'''を実行して' '' process.exit() '' 'を実行することができます。あなたのコードが書かれているので、楽しい時間を持たないつもりです – Wainage