【问题标题】:How to make promise wait until end of loop如何让承诺等到循环结束
【发布时间】:2017-07-04 19:21:04
【问题描述】:

我正试图将我的头脑围绕着承诺并有点挣扎。

这是代码:

// For Every row.
var prom = new Promise( (resolve, reject) => {

        existing_rows.forEach ((item,index) => {
            console.log("onto index: " + index);
            //We just need to set item[2]! 
            if (item[1].indexOf('%')===-1) {
                //Cool no percentage sign.
                translateClient.translate(item[1], 'th')
                    .then((results) => {
                        const translation = results[0];
                        console.log("translation is: " + translation);
                        item[2] = translation;
                     });
            }
        })

        resolve("Stuff worked!");
    })

prom.then(
    (result) => {
        //Cool that's finished.
        console.log("done!")
        console.log(JSON.stringify(existing_rows));
    }

)

existing_rows 只是我正在查看的一个数组,其中包含一些要使用 google api 进行翻译的内容。在我将其记录到 prom.then 块之前,我希望将所有翻译都放在 existing_rows 数组中。

目前,输出顺序如下:

onto index 0
onto index ..
onto index 8

done!
logs the array without the translations

translation is: ...... x 8

谢谢

【问题讨论】:

标签: javascript asynchronous promise es6-promise


【解决方案1】:

大概是这样的:

// For Every row.
Promise.all(existing_rows.map((item, index) => {
      console.log("onto index: " + index);
      // We just need to set item[2]! 
      if (item[1].indexOf('%')===-1) {
          // Cool no percentage sign.
          return translateClient.translate(item[1], 'th')
              .then((results) => {
                  const translation = results[0];
                  console.log("translation is: " + translation);
                  item[2] = translation;
              });
      }
}))
.then(result => {
    // Cool that's finished.
    console.log("done!")
    console.log(JSON.stringify(existing_rows));      
})

【讨论】:

  • 感谢您的回复,但 Jaromanda 首先发表了评论,暗示了同样的事情。
【解决方案2】:

使用 Promise.all 和 Array#map 代替新的 Promise 和 Array#forEach

var prom = Promise.all(existing_rows.map((item, index) => {
        console.log("onto index: " + index);
        //We just need to set item[2]! 
        if (item[1].indexOf('%') === -1) {
            //Cool no percentage sign.
            return translateClient.translate(item[1], 'th')
                .then((results) => {
                    const translation = results[0];
                    console.log("translation is: " + translation);
                    item[2] = translation;
                });
        }
        // see note 1
    })
);
prom.then(
    (result) => {
        //Cool that's finished.
        console.log("done!")
        console.log(JSON.stringify(existing_rows));
    }
)

[1] 这里没有返回值,但没关系,这相当于 return undefinedPromise.all 可以很好地处理非 Promises + Promises 的数组...

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 2020-05-15
    • 2013-12-20
    • 1970-01-01
    • 2017-09-07
    • 2018-10-13
    • 2017-12-16
    • 2022-12-08
    相关资源
    最近更新 更多