【发布时间】: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
谢谢
【问题讨论】:
-
建议你使用
Promise.all+Array#map而不是new Promise+Array#forEach -
并为地图中的每个“迭代”创建一个新的承诺?
-
啊,我会看看你的答案:P
-
@MikeMcCaughan - 我同意这些问题似乎很相似,有趣的是,没有一个已接受的答案可用于此代码
标签: javascript asynchronous promise es6-promise