如何做出承诺等到循环结束

时间:2017-02-15 22:14:26

标签: javascript asynchronous promise es6-promise

我正试图绕过承诺并挣扎一下。

这是代码:

// 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只是一个数组,我正在看一些使用谷歌api翻译的东西。我希望将所有翻译都放在existing_rows数组中,然后再将其记录在prom.then块中。

目前,输出顺序如下:

onto index 0
onto index ..
onto index 8

done!
logs the array without the translations

translation is: ...... x 8

由于

2 个答案:

答案 0 :(得分:1)

使用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可以正常使用非Promise + Promises ...

答案 1 :(得分:0)

粗略地说,像这样:

// 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));      
})