Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use a promise (in Typescript)

I’m comfortable with async\await\then etc. but was just experimenting and came across this and wanted to ask:

Let’s say I have this function:

HelloWorld():Promise<string>
  {
    return new Promise(resolve => {
      setTimeout(() => {
        alert("IN");
        resolve('Hello World!');
      }, 2000);
    });
  }

Now, I execute this function from another function like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

async onClick()
{
    var p:Promise<string> = this.HelloWorld();

    await(p);

    alert(p);
}

So, I’ll see alerts (after 2 seconds) in the following order:

‘IN’

‘[object Promise]’

My question is, by the time the second alert is called the promise has resolved (due to presence the await(p) call). So it’s value is determined (‘Hello World!’).

Can I access it’s value somehow other than using the usual .then type pattern ?

So, something like:

var p:Promise<string> = this.HelloWorld();

await(p);

alert(<VALUE OF PROMISE HERE (which now equals 'Hello World!')>);

Like I say, just experimenting and wondering.

>Solution :

Well, first, await is a keyword, not a function, so i am not sure what you are doing here.

When a promise is resolved, you can access its resolved value as a parameter in the callback of the then method, or, if it is awaited with await, you can assign directly the value to a variable.

So this

myPromise().then((value) => console.log(value));

Is the same as this

const value = await myPromise();
console.log(value);

So in your case you would just have to do this

const value = await p;

Or even

const value = await this.HelloWorld();

Also, no need to explicitly type the value here, as the return type of HelloWorld is already Promise<string>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading