NightmareJS循环中的异步操作,等待一切都要完成

时间:2018-04-16 08:29:05

标签: gulp nightmare

我有一个gulp任务,使用Nightmare访问一系列URL,从中提取SVG,处理它们并输出它们。

gulp.task('export', done => {
  const path = require('path');
  const Nightmare = require('nightmare');
  const nightmare = new Nightmare();
  const urls = ['http://one.com', 'http://two.org', 'http://three.net'];

  async function exportPDFs (items) {
    for (url of items) {
      const filename = path.parse(url).name;
      const selector = 'svg';
      await nightmare
        .goto(url)
        .wait(selector)
        .evaluate(selector => {
          let content;
          // Extract SVG from the page
          return content;
        }, selector)
        .then(
          svg => {
            // Heavy operation that takes long
            // How do I wait for this properly?
            processThing(filename);
            outputThing(filename);
          },
          err => console.error('Page evaluation failed', err)
        );
    }
    await nightmare.end().then(() => done()); // ???
  }

  exportPDFs(urls);
});

如何让它等待每次迭代的处理和输出,并在所有迭代结束时使用done()结束gulp任务?

目前在保存最后一个PDF之前结束:

Starting 'export'...
one.pdf saved
two.pdf saved
Finished 'export' after 3.2 s
three.pdf saved

1 个答案:

答案 0 :(得分:1)

processThingoutputThing转换为承诺。然后将它们链接起来,

.evaluate(()=>/*The code*/)
.then(processThing)
.then(outputThing)
.catch(e=>/*deal with errors*/)