【问题标题】:Why is my Angular Async/Await loop exiting before it execute for each index?为什么我的 Angular Async/Await 循环在为每个索引执行之前退出?
【发布时间】:2021-03-21 08:47:52
【问题描述】:

我在 Angular 中有一个 asnyc 函数,它在循环中完成所有等待调用之前退出。

它目前只运行 1 个等待调用。有什么想法吗?

  async rtClick() {
    for (let index = 0; index < this.mulObj.value.length; index++) {
      const selectedRT = this.mulObj.value[index];
      await this.runRTSub(selectedRT);
      console.log(index);
    }
    console.log('spot 2')

  }

在上面的示例中,即使数组中有 5 个对象,我也会在第一次等待完成后立即在控制台记录“spot 2”。我希望所有 5 个等待在“点 2”出现之前循环并完成。

下面是 runRTSub 调用的内容。

  runRTSub(selectedRT) {
    return new Promise((resolve) => {
      this.DbService.getRTSP(selectedRT).subscribe(rtsp_results => this.rtsp_results = rtsp_results,
      (err) => {
         console.log('ERROR: ' + JSON.stringify(err)); 
    },() => {
      resolve(1);
    });
  });
  }

【问题讨论】:

  • @NicholasTower -- 我添加了这个细节。我的问题是因为承诺吗?对不起,如果愚蠢的问题。

标签: angular typescript loops for-loop async-await


【解决方案1】:

等待承诺

您必须将您的承诺回调标记为async 以使其可等待。

下面是一个使用 setTimeout() 的简单例子来说明:

// returns 'done' after 500ms
function mockPromise() {
    /* NOTE: the promise callback has been marked async because we expect to await it later */
    return new Promise(async (res, rej) => {
    setTimeout(() => res("done"), 500)
  });
}

async function testMockPromise() {
    for(let i = 0; i < 5; i++) {
    console.log(await mockPromise());
  }
  console.log("final")
}
testMockPromise();
  /* outputs:
    done
    done
    done
    done
    done
    final /*

【讨论】:

  • 我添加了异步,但它仍然只运行循环的 1 次迭代,而不是预期的 5 次。我将循环设置为 console.log 索引,并在 for 循环在 rtClick 内完成后设置了“spot 2”的 console.log,我的日志如下所示:0 点 2 所以它运行索引 0,然后完成.这与我的不是以异步功能开头的事实有什么关系吗?或者我正在订阅?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
  • 1970-01-01
相关资源
最近更新 更多