我有一个这样的函数:
resulta = 0;
resultb = 0;
resultc = 0;
resultd = 0;
var wait = new promise((resolve, reject) => {
data.forEach((single,index,array) =>{
if (single.a == '1'){this.resulta = '1'}
else if (single.a=='2') {this.resultb = '2'}
else if (single.a=='3'){this.resultc = '3'}
else if (single.a=='4'){
this.function(single.a).then(async (bs) => {
if (somecondition) {
await bs.forEach(b => {
this.ccount = 0;
if(condition === true){
this.c = 'yes';
this.ccount = this.ccount +1;
}
});
}
if(this.ccount > 0){
this.resultd = '4';
}
else {
this.resultd = 'N/A';
}
}
}
if (index === array.length -1)resolve();
});
});
wait.then(async()=>{
console.log('count', this.count); // always is 0 but it should be something > 0
console.log('resulta', this.resulta); // 1 as it should be
console.log('resultb', this.resultb); // 2 as it should be
console.log('resultc', this.resultc); // 3 as it should be
console.log('resultd', this.resultd); // 0 and it should be or 4 or N/A
});所以这里的问题是,第一个foreach在第二个foreach之前结束,所以它解决了承诺,在结束第一个foreach之前,我如何等待第二个foreach (在最新的else if中)完成呢?
发布于 2020-11-10 11:12:48
您正在考虑promises应该在forEach块中工作得很好。不,不是那样的。你必须确保你内心的承诺应该得到适当的回报。然后,您可以创建promises数组,并使用Promise.all检查所有promises是否都已完成。
代码
const promises = data.map((single,index,array) =>{
if (single.a == '1'){ return this.resulta = '1' }
else if (single.a=='2') {return this.resultb = '2' }
else if (single.a=='3'){ return this.resultc = '3' }
else if (single.a=='4') {
return this.function(single.a).then((bs) => {
if (somecondition) {
bs.forEach(b => {
this.ccount = 0;
if(condition === true){
this.c = 'yes';
this.ccount = this.ccount +1;
}
});
}
if(this.ccount > 0){
this.resultd = '4';
}
else {
this.resultd = 'N/A';
}
}
}
});
Promise.all(promises).then(async()=>{
console.log('count', this.count);
console.log('resulta', this.resulta);
console.log('resultb', this.resultb);
console.log('resultc', this.resultc);
console.log('resultd', this.resultd);
});https://stackoverflow.com/questions/64762011
复制相似问题