0

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.

8
  • 1
    possible duplicate of How to return the response from an asynchronous call? Commented Apr 13, 2015 at 7: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. Commented Apr 13, 2015 at 7: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. Commented Apr 13, 2015 at 7:17
  • @thefourtheye I just want to know why the array validEmails doesn't fill with data using validEmails.push(email). Commented Apr 13, 2015 at 7:19
  • 1
    @KlevisMiho Trust me, its worth spending a day on it. Its a must read for all of us :-) Commented Apr 13, 2015 at 7:33

1 Answer 1

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();
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

is it possible for you to edit my function so the logic works? As I am still having trouble on how to do that.
modified my answer.Try it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.