if语句的foreach循环问题

时间:2019-04-08 11:55:48

标签: javascript if-statement foreach

为什么控制台日志显示此内容?

3 elem :
else
elem :
else
elem :
else
elem :
else
2 elem :
4 if

我期望输出:

 elem
 if 
 elem 
 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('');
  }
});

1 个答案:

答案 0 :(得分:1)

由于可观察对象异步发出事件,因此您的forEach循环将在执行对.subscribe的任何回调之前完成。

您可以通过将可观察对象变为承诺并await-对其进行解决。为了使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)。

相关问题