JohnnyAce
JohnnyAce

Reputation: 3749

How to get the value of a promise in an async / await function on typescript?

I have the following code:

export class AuthService {

  private key:string = "";

  constructor(private storage: Storage) {

  }

  private async getKey() {
    let response = await this.storage.get('key');
    return response;
  }

  public init() {
    this.key = this.getKey();
  }
}

But I get the following error: type promise any is not assignable to type string, the problem is with the return of getKey().

I want to set the value of this.key to the one stored on the Storage, I know I could use:

this.storage.get('key').then((val) => { this.key = val });

But I want to do it in a synchronous way.

Thank you very much

Upvotes: 2

Views: 3143

Answers (1)

user663031
user663031

Reputation:

key is a string. The return value of getKey, and all async functions, is a promise. You can't assign a promise to a string, as TypeScript is telling you. Instead, you have to wait for the promise (using then) and assign the value of the promise to key. So:

export class AuthService {

  private key:string = "";

  constructor(private storage: Storage) {

  }

  private async getKey() {
    let response = await this.storage.get('key');
    return response;
  }

  public init() {
    this.getKey().then(key => this.key = key);
  }
}

Or, you could make init itself an async function:

public async init() {
  this.key = await this.getKey();
}

but of course this.key still will not be populated until this.getKey() resolves, which won't be until this.storage.get resolves.

In many cases it will be better to "unwrap" the promise directly in the template, using the async pipe:

export class AuthService {

  public key: Promise<string>;

  constructor(private storage: Storage) { }

  ngOnInit() { this.key = this.storage.get('key'); }
}

// template

The key is {{key | async}}

But I want to do it in a synchronous way.

You can't. There is no way to make something asynchronous into something synchronous, other than a time machine. If something is going to happen in the future--whether 100ms, or 100 years--you have to wait for it. That's true whether you wait for the promise with promise.then() or await. await does not magically transform the future into the present. It is merely syntactic sugar that allows you to write your code in a way which looks synchronous, with the follow-up logic coming directly after the await, instead of inside a then handler.

Upvotes: 1

Related Questions