編集: サードパーティのライブラリを使用したくない場合は、独自のコードでこれを行う方法を次に示します。
/* jshint node:true*/
function getNotifications(responses, callbackToMainProgramLogic) {
'use strict';
var results = [];
function getNotificationAsync(response) {
getNotification(response.sender_id, function (data) {
results.push(data);
if (responses.length) {
getNotificationAsync(responses.pop());//If there are still responses, launch another async getNotification.
} else {
callbackToMainProgramLogic(results);//IF there aren't we're done, and we return to main program flow
}
});
}
getNotificationAsync(responses.pop());
}
getNotifications(someArrayOfResonses, function (dataFromNotifications) {
console.log('The collected data: ' + JSON.stringify(dataFromNotifications, 0, 4));
});
どうしてもやむを得ない場合は、このようなばかげたことをすることができます。loopUntilDatReceived のロジックは、空でない文字列を待つのではなく、配列サイズを待つことになりますが、考え方は似ており、とにかくこれを使用するべきではありません! :)
var fileData = '';
fs.readFile('blah.js', function (err, data) { //Async operation, similar to your issue.
'use strict';
fileData = data;
console.log('The Data: ' + data);
});
function loopUntilDataReceived() {
'use strict';
process.nextTick(function () {//A straight while loop would block the event loop, so we do this once per loop around the event loop.
if (fileData === '') {
console.log('No Data Yet');
loopUntilDataReceived();
} else {
console.log('Finally: ' + fileData);
}
});
}
loopUntilDataReceived();
これはばかげていると言いましたか?正直なところ、これはひどい考えですが、何が起こっているのか、Node イベント ループがどのように機能するのか、そしてなぜあなたが望むことができないのかを理解するのに役立つかもしれません。そして、コールバックとフロー制御ライブラリに関する他の投稿が進むべき道である理由.