Reputation: 1634
If in Typescript 1.7 / ES7 I have three functions:
async function f(): Promise<int> { /* ... */ }
async function g(): Promise<int> {
return f();
}
async function h(): Promise<int> {
return await f();
}
What would be the difference between these calls:
g();
h();
await g();
await h();
Upvotes: 1
Views: 647
Reputation: 3341
Calling an asynchronous function directly like g();
returns a Promise
that can be resolved/rejected:
g().then((result) => {
doSomethingWith(result);
doSomethingElseWith(result);
});
Returning a Promise
within another Promise
(which is what return f();
does) will resolve the outer promise with the value of the inner promise.
Just calling g()
will start whatever g
is doing and not waiting for its completion, discarding the result.
Calling g
with await
requires the enclosing scope to be an async
function as well, which conceptually "waits" for g
to "return" (to resolve/reject, actually).
Calling an asynchronous function with the await
keyword does basically the same thing as calling without await
and using a Promise
, just with a nicer syntax. So this:
async function f () { ... }
try {
var result = await f();
doSomethingWith(result);
} catch (error) {
handle(error);
}
is actually the same as this:
async function f() { ... }
f().then(
(result) => doSomethingWith(result),
(error) => handle(error)
);
Upvotes: 1