私はnode.jsにかなり慣れていないので、すべての要素がいつ処理されるかを知る方法を知りたいと思っています:
["one", "two", "three"].forEach(function(item){
processItem(item, function(result){
console.log(result);
});
});
...すべてのアイテムが処理されたときにのみ実行できることをしたい場合、どうすればよいですか?
私はnode.jsにかなり慣れていないので、すべての要素がいつ処理されるかを知る方法を知りたいと思っています:
["one", "two", "three"].forEach(function(item){
processItem(item, function(result){
console.log(result);
});
});
...すべてのアイテムが処理されたときにのみ実行できることをしたい場合、どうすればよいですか?
非同期モジュールを使用できます。簡単な例:
async.map(['one','two','three'], processItem, function(err, results){
// results[0] -> processItem('one');
// results[1] -> processItem('two');
// results[2] -> processItem('three');
});
async.map のコールバック関数は、すべてのアイテムが処理されるときに実行されます。ただし、processItem では注意が必要です。processItem は次のようにする必要があります。
processItem(item, callback){
// database call or something:
db.call(myquery, function(){
callback(); // Call when async event is complete!
});
}
forEach がブロックしています。次の投稿を参照してください。
JavaScript、Node.js: Array.forEach は非同期ですか?
すべてのアイテムの処理が完了したときに関数を呼び出すには、インラインで実行できます。
["one", "two", "three"].forEach(function(item){
processItem(item, function(result){
console.log(result);
});
});
console.log('finished');
処理する各アイテムの io バウンド負荷が高い場合は、Mustafa が推奨するモジュールを見てください。上記のリンク先の投稿で参照されているパターンもあります。
node.jsは今後ES6をサポートするため、他の答えは正しいですが、組み込みPromise
ライブラリを使用すると、より安定して整頓されると思います。
何かを要求する必要さえありません。Ecma はPromises/A+ライブラリを採用し、それをネイティブ Javascript に実装しました。
Promise.all(["one", "two","three"].map(processItem))
.then(function (results) {
// here we got the results in the same order of array
} .catch(function (err) {
// do something with error if your function throws
}
Javascript は、デバッグに関してはかなり問題のある言語 (動的型付け、非同期フロー) でpromise
あるため、コールバックの代わりに s を使用することで、最終的に時間を節約できます。