Javascript 如何让承诺一直等到循环结束
我正试着把我的头绕在承诺上,并且有点挣扎 代码如下:Javascript 如何让承诺一直等到循环结束,javascript,asynchronous,promise,es6-promise,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]!
// 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));
}
)
现有的_行只是一个数组,我正在使用GoogleAPI翻译一些东西。我希望在将其记录到prom.then块之前,将所有翻译都放在现有的_行数组中
目前,输出顺序如下:
onto index 0
onto index ..
onto index 8
done!
logs the array without the translations
translation is: ...... x 8
大致地说谢谢,像这样:
// 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));
})
使用Promise.all和Array#map代替新的Promise和Array#forEach
[1] 这里没有返回值,但没关系,这相当于
returnundefined
和Promise。所有的都适用于非承诺+承诺的数组 建议您使用Promise.all
+Array#map
而不是newpromise
+Array#forEach
并为地图中的每个“迭代”创建一个新的承诺?啊,我会查看您的答案:p网站上已经有很多关于这方面的问题。请看,…@MikeMcCaughan-我同意这些问题似乎是相似的,有趣的是,所有被接受的答案都不适用于此代码感谢您的回复,但Jaromanda首先评论了同样的问题。
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));
}
)