gpt4 book ai didi

node.js - 如何异步执行多个 Nightmare 函数

转载 作者:太空宇宙 更新时间:2023-11-04 02:21:39 26 4
gpt4 key购买 nike


我正在使用 Nightmare 抓取网页,并且想知道如何在输入数组上重用函数。

假设我有一种方法来检索页面标题

function* test(url,callback) {
var size = { width: 1920, height: 1080, 'use-content-size': true, show: true }

var nightmare = Nightmare(size)
var title = yield nightmare
.goto('http://cnn.com')
.evaluate(function () {
return document.title
});
console.log(title)
yield nightmare.end()
callback()
}

我想对一组 url 执行此方法。因此,我使用异步库来在整个数组上运行并在 urls url 数组上执行 test 函数。

async.each(urls, test, function (err) {
console.log('done!');
});

但是async.each不支持生成器函数,我如何将测试函数更改为普通函数而不是生成器函数。

最佳答案

我找到了一种方法来做到这一点 - 我需要使用 Promise 库来执行多个函数,并且它是一个普通函数。

function test(url){
Promise.resolve( // call for the promises library with the nightmare instance
nightmare
.goto() //all the calls that you need
.wait()
.....
).then(function (result) { //This function will be called when the block of commands is done , with the result.
console.log("Done")
}, function (err) { //Error handling
console.log(err);
});
}

关于node.js - 如何异步执行多个 Nightmare 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33085985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com