【问题标题】:Nightmare then() invokes immediately after evaluate()Nightmare then() 在 evaluate() 之后立即调用
【发布时间】:2017-11-18 00:24:47
【问题描述】:

考虑以下代码sn-p:

nightmare
    .evaluate(function (resolve){
        setTimeout(function () {
            resolve(null, 1234);
        }, 1500)
    })
    .then(function (result) {
        console.log('SUCCESS', result);
    })
    .catch(function (e) {
        console.log('ERROR', e);
    });

假设nightmare实例之前已经初始化过,我也用过goto()inject()等方法(那部分代码非常庞大,但如果需要我可以尝试清理它以呈现在那里) .但我最终得到的结果 - 不太可能是SUCCESS null 而不是SUCCESS 1234

我正在对此进行试验,并且了解到如果在该链中在 .evaluate() 之前调用 .wait(15000)(或在 .goto() 之后和 .evaluate() 之前设置断点并在它被触发时等待一段时间),代码按预期工作。

这段代码有什么问题?

【问题讨论】:

  • resolve(null, 1234) 为什么传递 null 但期望 1234
  • 因为如果按照规范,第一个参数是一个错误的结果(而不是使用reject())被传递给catch()。但是我需要调用then() 函数,所以我将null 作为第一个参数传递。虽然这实际上并不重要。真正重要的是then() 雇用 setTimeout() 完成并调用resolve()
  • 您不返回任何东西。 documentation of .evaluate 中有一个使用 Promises 的示例。
  • 基于噩梦的文档 - 你使用 .evaluate 错误
  • @JaromandaX,真的吗?从文档中复制粘贴:If the arguments passed are one fewer than the arguments expected for the evaluated function, the evaluation will be passed a callback as the last parameter to the function.。我不应该返回任何东西,因为我正在使用 setTimeout() 函数来解决延迟的承诺(在 1500 毫秒内)。如果我要返回一些东西,它应该不会有任何影响,因为evaluate() 内部的回调函数有一个额外的参数来解决噩梦般的承诺。

标签: node.js web-scraping electron es6-promise nightmare


【解决方案1】:

考虑以下答案,

nightmare
    .evaluate(function (){
       return new Promise((resolve, reject)=>{        
        setTimeout(function () {
            resolve(1234);
        }, 1500)
       })
    })
    .then(function (result) {
        console.log('SUCCESS', result);
    })
    .catch(function (e) {
        console.log('ERROR', e);
    });

它有什么作用?它返回一个承诺。所以代码会一直等到解决。

此外,如果您想获得 1234,则必须解析 1234,而不是 null

了解有关承诺的更多信息,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-08
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    相关资源
    最近更新 更多