为什么控制台日志最后会显示所有“if”输出?
3 elem :
else
elem :
else
elem :
else
elem :
else
2 elem :
4 if
我期望输出:
elem
if
elem
else ...
我认为它会在每个“elem”之后显示“if”或“else”!
这是代码:
res.docs.forEach((elem) => {
console.log('elem');
if (elem.productType) {
this.Service.function(elem.productType._id).subscribe((result) => {
console.log('if');
const text = result.name;
this.marketPlaceList.push(text);
});
} else {
console.log('else');
this.marketPlaceList.push('');
}
});
由于 observable 异步发出事件,您的forEach
循环将在.subscribe
执行任何回调之前完成。
您可以通过将 observable 转换为 promise 并对其进行await
-ing来解决此问题。为了await
工作,您需要一个async
函数,因此将您的代码包装到这样的函数中,并将forEach
循环更改为for
循环:
(async () => { // Async wrapper
for (const elem of res.docs) { // Use for-loop
console.log('elem');
if (elem.productType) {
// Convert observable to promise, and await
const result = await this.Service.function(elem.productType._id).toPromise();
console.log('if');
const text = result.name;
this.marketPlaceList.push(text);
} else {
console.log('else');
this.marketPlaceList.push('');
}
}
)(); // execute immediately
当您需要完全填充数组时,请确保也等待最外层的async
函数(或then
在其上使用)this.marketPlaceList
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句