【问题标题】:Why is value returned before asynchronous call is resolved, even when using async/await?为什么在异步调用解决之前返回值,即使使用 async/await?
【发布时间】:2019-07-01 20:40:42
【问题描述】:

以下函数在this.codesService.getCostCodes()解析之前返回Promise,导致未定义

  async getTopParentByChildId(id: string) {
    let parent;

    await this.codesService.getCostCodes().subscribe( data => {
      parent = data.body[0];
    });

    return new Promise<BidItem>(resolve => {           //returning `parent` results in the same issue
      resolve(parent);
    });

  }

getTopParentByChildId() 正在被另一个异步函数调用,该函数具有相同的问题,即它在解决异步调用之前返回 undefined:

  async populateBidItemObjectArray(node){
    const parent = await this.getTopParentByChildId(node.id);    //should wait for function to return before executing the rest

    const bidItem = {
      name: parent.name,
      id: parent.id
    };

    return new Promise<BidItem>(resolve => {     //returns undefined before this.getTopParentByChildId is resolved
      resolve(parent);
    });
  }

我已经阅读了很多关于 async/await 和 Promise 的内容,但到目前为止,我尝试过的解决方案都没有对我有用。我无法理解为什么当我使用 async/await 关键字时它不等待异步函数解析。

【问题讨论】:

  • 你可以awaitPromise 就可以了。你不能等待 rxjs 订阅(甚至是 rxjs 可观察的,这会更有意义)。
  • 在这里使用new Promise 没有意义。你想写return Promise.resolve(parent),但即使这样也没有必要——在async function,你可以写return parent;

标签: javascript typescript asynchronous


【解决方案1】:

你可以awaitPromise 就可以了。你不能等待一个 rxjs 订阅(甚至是一个 rxjs 可观察的,这会更有意义但仍然无法工作)。

您可以将 getTopParentByChildId 重构为此删除异步/等待,因为它们不需要。

getTopParentByChildId(id: string) {
  return this.codesService.getCostCodes()
    .pipe(map(data => data.body[0]))
    .toPromise();
}

您可以将populateBidItemObjectArray 重构为此。

populateBidItemObjectArray(node) {
  return this.getTopParentByChildId(node.id)
    .then(_ => {
      return {
          name: _.name,
          id: _.id
        };
    });
}

【讨论】:

    猜你喜欢
    • 2019-04-05
    • 2017-10-26
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 2020-05-03
    • 2021-06-06
    • 2019-03-03
    相关资源
    最近更新 更多