Issue
Let's say I have two async functions:
async f(): Promise<void> {
flag = true;
await computation();
}
async g(): Promise<void> {
doPreparation(); // synchronous
f();
}
As far as I understand, if I prepend f()
call with await
, then at this point the runtime is free to schedule the execution of f
at a later time and some other code may be chosen to be run meanwhile.
What I want is to make g
pass execution to f
synchronously, i.e. flag = true
should run strictly after doPreparation()
without yields (I don't expect computation()
to be run synchronously too). This seems like a fair request since f
is the last action in g
.
Is there a guaranteed way to run an async f
this way?
Solution
Either way, with await f()
or just f()
, then f()
will be called immediately when the interpreter hits that line of code.
The difference for await
is when the NEXT line of code is executed.
For the last line of code in your async
function, you can just do:
return f();
There is no need to use await
on the last line of the async
function unless you also have it surrounded by a try/catch
and are trying to catch the rejection locally within the function.
So, these two are identical:
async g(): Promise<void> {
doPreparation(); // synchronous
return f(); // asynchronous, f() returns a promise
}
and
async g(): Promise<void> {
doPreparation(); // synchronous
let x = await f(); // asynchronous, f() returns a promise
return x;
}
Or, if the promise that f()
returns has an undefined resolved value, then this is also the same:
async g(): Promise<void> {
doPreparation(); // synchronous
await f(); // asynchronous, f() returns a promise
}
This, would NOT be the same:
async g(): Promise<void> {
doPreparation(); // synchronous
f(); // asynchronous, f() returns a promise
}
because in this case, the promise that g()
returns would resolve BEFORE the promise that f()
returns was resolved. In fact, the promise that g()
returns would be entirely disconnected from the f()
promise. In this case, f()
is fire and forget with no way for anyone to know when it's done or any way for anyone to catch/handle its error. If f()
rejects in this last scenario, then your app will get an unhandled rejection which is never a good thing.
Answered By - jfriend00
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.