繁体   English   中英

ForEach 等待 Observable 订阅

[英]ForEach wait for Observable Subscription

我有这个数组orderCodes ,其中包含特定订单的代码,然后使用代码我可以获得该订单的详细信息(每个订单有多个产品),我需要在订单详细信息中提取每个产品的代码。

getOrderDetails()是一个带有resultsObservable (产品数组),每个result都有一个我需要的code

    this.orderCodes.forEach((orderCode) => {

      loadOrderDetails(orderCode);

      getOrderDetails().subscribe((order: any) => {
        if (order.results) {
          order.results.map((result) => {
            console.log(result.code);
          });
        }
      });

    });

我已经尝试过这个forEach但由于我订阅了Observable forEach 跳到下一次迭代,我需要它等待

有任何想法吗?

rxjs 方式将是

from(this.orderCodes).pipe(
  concatMap((orderCode) =>  // concatMap operator makes your items come "in order" one after another
    defer(() => {
      loadOrderDetails(orderCode);

      return getOrderDetails();

    }))
).subscribe((order: any) => {
  if (order.results) {
    order.results.map((result) => {
      console.log(result.code);
    });
  }
});

或者您可以转换为承诺并使用异步等待(更优雅,但在 angular 中通常不太喜欢的方式,因为如果做错了转换为承诺和更改检测问题,但这取决于......)

async myFunctionThatDoesAllThis(...) {
....
for(let orderCode of this.orderCodes) {
  loadOrderDetails();
  const order = await getOrderDetails().pipe(take(1)).toPromise(); // pipe(take(1)) could be skipped if getOrderDetails is just an http request.
  if(order.results) {
     order.results.forEach((result) => {
        console.log(result.code);
     });
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM