bollin
bollin

Reputation: 355

details of async/await in typescript

I have read various introduction texts about the topic but I still struggle with the details (in nodejs).

async function a() {
    const e = await Promise.resolve(42);
    console.log(e);
    return e;
}
const b = a();
console.log(b);

displays

Promise { <pending> }
42

What is explanation for b and e not being the same? After removing await I am getting

Promise { 42 }
Promise { <pending> }

Again not the same. Replacing the right side of e initialization by the plain number 42 gives me a another promise for b

42
Promise { 42 }

Can you explain it?

Upvotes: 1

Views: 401

Answers (3)

Bruno Grieder
Bruno Grieder

Reputation: 29814

A practical way to look at it is that inside an async function, after an await, your are in a then i.e.

async function a(): Promise<number> {
    const e = await Promise.resolve(42);
    //now "in a then"
    console.log('e',e);
    return e;
}

is somewhat (await waits) equivalent to

function a(): Promise<number> {
    return Promise.resolve(42)
      //now "in a then"
      .then(e => {
        console.log('e',e);
        return e;
      })
}

Upvotes: 0

fregante
fregante

Reputation: 31688

The async function pauses when it finds await, while the code outside it continues.

In short when console.log(b) is executed, the async function has not yet resolved so you get the <pending> state. In the next tick the promise resolves, the async function continues you get the 42 in there.

In your last part, await doesn't pause the function because there's no promise, so you get the 42 right away.

Upvotes: 0

basarat
basarat

Reputation: 276191

Because its async!

You think that e is printing before b. But that is not the case. b is pointing to the final promise of calling a (hence b Promise). While a executes e only comes out from yield result ( e = await somPromise). So e points to the resolved value.

The following is helpful :

async function a() {
    const e = await Promise.resolve(42);
    console.log('e',e);
    return e;
}
const b = a();
console.log('b',b);

which prints

b Promise { <pending> }
e 42

More

some docs https://basarat.gitbooks.io/typescript/content/docs/async-await.html

Upvotes: 1

Related Questions