【问题标题】:In Node.js, es6, how do you make a loop wait for an async process?在 Node.js、es6 中,如何让循环等待异步进程?
【发布时间】:2018-02-05 12:59:29
【问题描述】:

我知道 js 中的循环不会等待异步过程,因此,当异步过程完成时,将始终处于最后一次迭代。

我的问题是,如何解决这个问题,以便让 for 循环等待循环的每次迭代?

getChildItems() {
return new Promise((resolve, reject) => {

  this.lessons.levels.map((item, i) => {

      item.childlevels.map((childItem, iChild) => {

        ((i, iChild) => {
        this.horseman
        .open(childItem.url)
        .html()
        .then((html) => {
          cheerio(html).find('.list-item a').map((index, elem) => {
            let lesson = cheerio(elem);
            childItem.lessons.push(
              {name: lesson.text(), url: lesson.attr('href')}
            );
          });
        })
        .then(() => {
          const outter = i >= this.lessons.levels.length - 1;
          const inner = iChild >= item.childlevels.length - 1;

          if (outter && inner) {
            resolve(this.lessons);
          }
        });
      })(i, iChild);
      });
  });

});
}

【问题讨论】:

标签: javascript node.js asynchronous async.js


【解决方案1】:

将异步调用放在循环中是一种不好的做法。你有两种方法来处理这个问题。


1 - 你希望函数被并行调用

使用Promise.all。例如:

const rets = await Promise.all(this.lessons.levels.map(...));

2 - 您希望函数一个接一个地调用

this stackoverflow post 中的示例。

【讨论】:

  • 在使用 await 时遇到问题,我将异步添加到它所在的箭头函数中,但出现错误:SyntaxError: missing ) after argument listreturn new Promise(async function (resolve, reject) {
  • 您可以使用 async/await (ES8),也可以使用 Promise (ES6)。 async function() {function() { return new Promise(
  • Promise.all 使用 async/await await Promise.all(...);使用承诺Promise.all(...).then(...).catch(...)
  • 谢谢,但现在我似乎收到了错误'Unhandled rejection HeadlessError: Phantom Process died,我猜这是因为无头浏览器在发出请求之前就关闭了,这意味着我做错了。我对 Node.js 还很陌生,请您举例说明在 Promise.all() 中要做什么,因为它似乎目前没有等待发出请求。 (我用的是ES6版本)
【解决方案2】:

您可以使用BluebirdPromise.each。这会在运行下一次迭代之前等待您的承诺返回

Promise.each([item1,item2,item3,item4], function(item, index) => {
  // data manipulation with item if needed
  return Promise.resolve(async_action(with_item))
})

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 2021-10-18
    • 1970-01-01
    • 2013-01-01
    • 2017-01-31
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    相关资源
    最近更新 更多