编辑:如果您不想使用第三方库,这是在您自己的代码中执行此操作的方法。
/* 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 事件循环是如何工作的,以及为什么您想要的东西是不可能的。以及为什么其他关于回调和流控制库的帖子是要走的路。