访问节点js中的函数之外的数组

我知道node.js是asynchronous运行的,所以外部函数比inner更早执行。 但是,在for循环之外访问通知数组的方式是什么? 我想立即访问数组中的所有值,这是可行的吗?

var notification=[]; for(var j=0;j<6; j++) { getNotification(response[j].sender_id,function(results) // a function called { notification[j] =results; console.log(notification); // output: correct }); } console.log(notification); // output: [], need notification array values here 

编辑:如果你不想使用第三方库,这是如何在你自己的代码中做到这一点。

 /* 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中的逻辑将等待数组大小,而不是等待非空string,但是这个想法是相似的,您不应该使用这个! 🙂

 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事件循环如何工作,以及为什么您想要的是不可能的。 为什么其他职位关于callback,stream量控制库是要走的路。

首先,您的代码中存在closures问题(请参阅此处的详细信息)

然后,你只是不能在循环旁边有数组值,因为这个值在这个时候还没有准备好。 您需要等到所有6个getNotification调用得到解决。 你可以用asynchronous库来做到这一点。 就像是:

 var notification = []; function createRequest (index) { return function (callback) { getNotification(response[index].sender_id, function(results) { notification[index] = results; callback(results); }); } } var requests = []; for(var j=0;j<6; j++) { requests.push(createRequest(j)); } async.parallel(requests, function (allResults) { // notifications array is ready at this point // the data should also be available in the allResults array console.log(notifications); }); 

将callback发送到通知循环,如下所示:

 var notification=[]; getNotificationArray( function() { console.log(notification); }); function getNotificationArray (callback) { for(var j=0;j<6; j++) { getNotification(response[j].sender_id,function(results) // a function called { notification[j] =results; console.log(notification); // output: correct }); } callback(); }