1

I have a NodeJS + Phantom project, and I have the following function:

function isLogged(page) {
    var logged = false;
    page.evaluate(function() {
        return document.querySelector(".login") != null;
    }, function(bl) {
        console.log("1");
        logged = bl;
    });
    console.log("2");
    return logged;
}

But this function prints "2" before "1". How can I fix it?

Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78

1 Answers1

0

You're using a bridge between node.js and PhantomJS. PhantomJS runs as a separate process which means that every communication is done asynchronously. You can't return a result that is calculated asynchronously. The easy solution is to use a callback function:

function isLogged(page, callback) {
    page.evaluate(function() {
        return !!document.querySelector(".login");
    }, callback);
}

and use it like this:

isLogged(page, function(res){
    console.log(res);
});

This won't return anything.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222