首页 > 解决方案 > nightmare.js, on .evaluate this gives me an error on node

问题描述

I'm trying to paginate by scrolling,(by clicking a button). but when i want to add some delay to that action with 'await new Promise' node gives an error on run time how to escape this from node run time this is the code snippet,

 let scrapedData = yield nightmare
    .goto(nextExists)
    .wait(3000)
    .evaluate(function () {

      var links = [];
      var productList = "";
      var flag = true;

      while (flag) {
        var element = document.querySelectorAll('.load-more');
        console.log('aa ' + element[0].style.display == "");
        if (element[0].style.display == "") {
          element[0].click()
        } else {
          flag = false
        }
        await new Promise(resolve => setTimeout(resolve, 3000)); // error
        /*
        await new Promise(resolve => setTimeout(resolve, 3000));
                      ^^^
        SyntaxError: Unexpected token new
            at createScript (vm.js:80:10)
            at Object.runInThisContext (vm.js:139:10)
            at Module._compile (module.js:599:28)
            at Object.Module._extensions..js (module.js:646:10)
            at Module.load (module.js:554:32)
            at tryModuleLoad (module.js:497:12)
            at Function.Module._load (module.js:489:3)
            at Function.Module.runMain (module.js:676:10)
            at startup (bootstrap_node.js:187:16)
            at bootstrap_node.js:608:3
        */
      }
      console.log('all done')
})

标签: node.jspromisenightmare

解决方案


您在async这里缺少关键字.evaluate(async function {})

这是您要实现的目标的最小示例:

const Nightmare = require('Nightmare');
const nightmare = new Nightmare({show: true});

const scrapedData = nightmare
    .goto('http://google.com')
    // You can use `await` keyword only in `async` functions
    // Async function *always* returns a promise which nightmare knows how to handle
    .evaluate(async function () {
        await new Promise(resolve => setTimeout(resolve, 3000));
    })
    .end()
    .then(() => console.log('All done'));

async/await 例如,您可以在此处阅读更多信息。


推荐阅读