由于 Nightmare可以,你可以像普通的 Promises 一样then
从 a 中返回它来链接它。.then()
var Nightmare = require('nightmare');
var nightmare = Nightmare({
show: true,
paths: {
userData: '/dev/null'
}
});
nightmare
.goto('http://www.example.com/')
.wait('h1')
.evaluate(function() {
return document.querySelector('title')
.innerText;
})
.then(function(title) {
if (title == 'someTitle') {
return nightmare.goto('http://www.yahoo.com');
} else {
return nightmare.goto('http://w3c.org');
}
})
.then(function() {
//since nightmare is `then`able, this `.then()` will
//execute the call chain described and returned in
//the previous `.then()`
return nightmare
//... other actions...
.end();
})
.then(function() {
console.log('done');
})
.catch(function() {
console.log('caught', arguments);
});
如果您想要一个看起来更同步的逻辑,您可能需要考虑使用带有vo或co的生成器。例如,上面重写为:vo
var Nightmare = require('nightmare');
var vo = require('vo');
vo(function * () {
var nightmare = Nightmare({
show: true,
paths: {
userData: '/dev/null'
}
});
var title = yield nightmare
.goto('http://www.example.com/')
.wait('h1')
.evaluate(function() {
return document.querySelector('title')
.innerText;
});
if (title == 'someTitle') {
yield nightmare.goto('http://www.yahoo.com');
} else {
yield nightmare.goto('http://w3c.org');
}
//... other actions...
yield nightmare.end();
})(function(err) {
if (err) {
console.log('caught', err);
} else {
console.log('done');
}
});