PhantomJS 5分钟Wiki phantom.exit()奇怪

Bre*_*dly 3 javascript phantomjs

所以维基的例子phantom.exit()在这里有两个地方.为什么我不能放在phantom.exit()剧本的最后?这对我来说没有多大意义.

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?
Run Code Online (Sandbox Code Playgroud)

Jam*_*ice 6

page.open方法是异步的,因此传递给它的回调函数将在未来的某个时刻运行(当所引用的资源address已完成加载时).

如果你phantom.exit()在该脚本结束时调用,PhantomJS将在回调有机会执行之前退出.