Klevis Miho
Klevis Miho

Reputation: 859

Why data isn't being added to array in NodeJS

What is wrong with my code:

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

var emails = ['[email protected]', '[email protected]'];
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
});

The validEmails array isn't being populated.

Upvotes: 0

Views: 45

Answers (1)

sachin.ph
sachin.ph

Reputation: 1078

It is because

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

is outside the callback.So it executed before executing the callback.You will have to use validEmails after every thing has been added or all callback completed.

You can use underscore's after for these kind of things.

you can try with

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();
    });
});

Upvotes: 1

Related Questions