当我试图加载一个页面(从codefights.com)并等待特定的html元素加载时,我收到了一个“未处理的承诺拒绝”。
下面是我的代码:
import * as Nightmare from 'nightmare';
const nightmare = Nightmare({ show: true });
nightmare
.goto('https://codefights.com/interview/EDaACHNYHyH6qQFAL')
.wait('body > div:nth-child(9) > div > div.page--header > div > span')
.evaluate((selector) => {
return document.querySelector(selector);
}, 'body > div:nth-child(9) > div > div.page--header > div > span')
.end()
.then((functionTitle) => {
console.log(functionTitle);
});以下是例外情况:
Unhandled promise rejection (rejection id: 1): Error: Evaluation timed out after 30000msec. Are you calling done() or resolving your promises?
对如何解决这个问题有什么想法吗?
发布于 2017-05-11 07:03:41
在深入研究了the documentation a bit more之后,我发现如果evaluate后面跟了Promise,那么它应该返回一个then。
还支持将
Promise作为evaluate的一部分。如果函数的返回值有then成员,则.evaluate()假定它正在等待promise。
下面是它修复后的样子:
nightmare
.goto(url)
.wait('body > div:nth-child(9) > div > div.page--header > div > span')
.evaluate((selector) => {
return new Promise((resolve, reject) => {
try {
resolve(document.querySelector(selector).innerText);
} catch (exception) {
reject(exception);
}
});
}, 'body > div:nth-child(9) > div > div.page--header > div > span')
.end()
.then((functionTitle) => {
console.log(functionTitle);
});发布于 2017-05-11 06:29:48
要处理拒绝,只需将.catch(handler)链接到链或将处理程序作为第二个参数传递给最终的chain
nightmare
.goto('https://codefights.com/interview/EDaACHNYHyH6qQFAL')
.wait('body > div:nth-child(9) > div > div.page--header > div > span')
.evaluate(selector => {
return document.querySelector(selector);
}, 'body > div:nth-child(9) > div > div.page--header > div > span')
.end()
.then(functionTitle => {
console.log(functionTitle);
}, error => {
console.error(error);
});https://stackoverflow.com/questions/43903166
复制相似问题