0

What is wrong with my code:

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

The validEmails array isn't being populated.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Klevis Miho
  • 851
  • 8
  • 15
  • 1
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – thefourtheye Apr 13 '15 at 07:10
  • In addition to wrong way of checking results of asynchronous method there is very good possibility that gmail and other open servers will simply refuse to provide information need for "email-existence" to detect valid e-mail addresses. – Alexei Levenkov Apr 13 '15 at 07:14
  • @AlexeiLevenkov I did some testing, and this script returns true when passing valid emails, but I believe that some servers will refuse to provide this information. – Klevis Miho Apr 13 '15 at 07:17
  • @thefourtheye I just want to know why the array validEmails doesn't fill with data using validEmails.push(email). – Klevis Miho Apr 13 '15 at 07:19
  • @KlevisMiho Did you check the linked dup post? – thefourtheye Apr 13 '15 at 07:22
  • @thefourtheye sure thanks, but I am new to Nodejs and this post is too overwhelming for me. – Klevis Miho Apr 13 '15 at 07:24
  • 1
    @KlevisMiho Trust me, its worth spending a day on it. Its a must read for all of us :-) – thefourtheye Apr 13 '15 at 07:33
  • @thefourtheye seems like it's worth a read, thanks :) – Klevis Miho Apr 13 '15 at 07:34

1 Answers1

1

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();
    });
});
sachin.ph
  • 1,078
  • 12
  • 24