我知道node.js是异步运行的,所以外部函数比内部函数执行得更早。但是在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
答案 0 :(得分:1)
编辑:如果您不想使用第三方库,这是在您自己的代码中执行此操作的方法。
/* 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事件循环如何工作,以及为什么您想要的是不可能的。以及为什么关于回调和流量控制库的其他帖子是可行的方法。
答案 1 :(得分:0)
将回调发送到通知循环,如下所示:
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();
}
答案 2 :(得分:0)
首先,您的代码中存在关闭问题(请参阅详细信息here)
然后,您根本无法在循环旁边拥有数组值,因为此时值尚未就绪。 您需要等到所有6个getNotification调用都得到解决。您可以使用async库执行此操作。类似的东西:
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);
});