Robert
Robert

Reputation: 511

Why is value returned before asynchronous call is resolved, even when using async/await?

The following function returns the Promise before this.codesService.getCostCodes() resolves, resulting in undefined

  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() is being called by another asynchronous function that has the same issue where it returns undefined before resolving the async call:

  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);
    });
  }

I've read a lot about async/await and promises, but none of the solutions I've tried have worked for me so far. I'm unable to understand why it's not waiting for the async functions to resolve when I'm using the async/await keywords.

Upvotes: 0

Views: 72

Answers (1)

Igor
Igor

Reputation: 62248

You can await a Promise and that is it. You can't await a rxjs subscription (or even an rxjs observable which would have made more sense to try but still won't work).

You can refactor getTopParentByChildId to this which removes the async/await as they are not needed.

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

You can refactor populateBidItemObjectArray to this.

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

Upvotes: 1

Related Questions