为什么数据没有被添加到NodeJS中的数组中

时间:2015-04-13 07:06:43

标签: arrays node.js

我的代码有什么问题:

var emailExistence = require('email-existence');

var emails = ['klevisi@gmail.com', 'workingemail@gmail.com'];
var validEmails = [];


emails.forEach(function(email) {
    emailExistence.check(email, function(err, res) {
        if(res == true) {
            validEmails.push(email); //No email is being added
            console.log(email); //Emails are written to the console
        }
    });
});

validEmails.forEach(function(email) {
    console.log(email); //Nothing is written to the console
});

未填充validEmails数组。

1 个答案:

答案 0 :(得分:1)

这是因为

validEmails.forEach(function(email) {
console.log(email); //printed at last
});

在回调之外。所以它在执行回调之前执行。在添加完所有内容或完成所有回调后,你必须使用validEmails

您可以将underscore's after用于此类事情。

你可以试试

var _U = require('underscore');
var afterAllEmailChecks = _U.after(emails.length,function(){
    validEmails.forEach(function(email) {
        console.log(email); //Nothing is written to the console
    });
});
emails.forEach(function(email) {
    emailExistence.check(email, function(err, res) {
        if(res == true) {
            validEmails.push(email); //No email is being added
            console.log(email); //Emails are written to the console
        }
       afterAllEmailChecks();
    });
});