简体   繁体   中英

PhantomJS javascript wait until function complete

I have a problem with a PhantomJS script. The script gets a JSON encoded string from a web page and does other things with it. The script:

var address = address;
var amount = 0;

function changeAmount()
{
   var page=require('webpage').create();
   page.open (address, function(){
     //parse json, set amount to something (usually 4)
     amount = 4;
  });
}

changeAmount();
console.log(amount); //prints 0

//Do stuff with amount

phantom.exit(); //amount not changed yet.

How can I check if the changeAmount function is finished before going forward? Timeout is not possible since I don't know the time it takes to process the changeAmount.

You can use a callback, like so:

function changeAmount(callback) {
    var page=require('webpage').create();
    page.open (address, function () {
        //parse json, set amount to something (usually 4)
        amount = 4;
        callback();
    });
}

changeAmount(function () {
    // This function runs when callback() (above) is reached
    console.log(amount);

    //Do stuff with amount

    phantom.exit();
});

And if you're not using the amount variable elsewhere, you could eliminate it by passing it as an argument to the callback:

changeAmount(function (amount) {

and then

callback(amount); // or callback(4);

page.open() is an inherently asynchronous function. The only reliable way to do this is to use callbacks in the PhantomJS script:

var address = address;

function changeAmount(callback)
{
   var page = require('webpage').create();
   page.open (address, function(){
     //parse json, set amount to something (usually 4)
     var amount = 4;
     callback(amount);
  });
}

You can even go as far as passing amount into that callback to remove the global variable.

After that, you will need to write your script using that callback pattern.

changeAmount(function(amount){
    console.log(amount);

    //Do stuff with amount

    phantom.exit();
});

Furthermore, you probably shouldn't create a new page every time you call changeAmount() (if you do this repeatedly). You can reuse the same page . If you think that creating a new page gives you a fresh environment to work in, then you're mistaken. It is just like a new tab. It will use the same session as all the other pages that you have created.

If you do this often, this will lead to a memory leak, because you're not closing the previously opened pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM