So the example from the wiki has phantom.exit() in two places here. Why can’t I just put phantom.exit() at the end of the script? It doesn’t make too much sense to me.
var page = require('webpage').create(),
t, address;
if (phantom.args.length === 0) {
console.log('Usage: loadspeed.js <some URL>');
phantom.exit(); //Why does this only work if "phantom.exit()" is here,
} else {
t = Date.now();
address = phantom.args[0];
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
} else {
t = Date.now() - t;
console.log('Loading time ' + t + ' msec');
}
phantom.exit(); //and here.
});
}
// but not just a single one here?
The
page.openmethod is asynchronous, so the callback function you pass to it will run at some point in the future (when the resource referred to byaddresshas finished loading).If you put a call to
phantom.exit()at the end of that script, PhantomJS will exit before the callback has had a chance to execute.