How to make promise wait until end of loop
我正试图将我的头脑围绕在Promise上,并有点挣扎。
这是代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // 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 数组中。
目前的输出顺序是:
1 2 3 4 5 6 7 8 | onto index 0 onto index .. onto index 8 done! logs the array without the translations translation is: ...... x 8 |
谢谢
使用 Promise.all 和 Array#map 而不是 new Promise 和 Array#forEach
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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] 这里没有返回值,但没关系,这相当于
大致如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // 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)); }) |