I have an async function
async function f1 (){
some db operation
return result
}
What is the difference between the two code
await f1()
.then((result)=> something1. Can I use result here?)
vs
f1()
.then((result)=>something2. Can I use result here?)
3
Answers
To answer your immediate question: "Is using await necessary with
then
": no.The two examples in your question aren’t really comparable. Both examples are the same but in the first you’ve mysteriously added a redundant
await
keyword.The question you should ask is "What are the different approaches to using promises?" something that MDN covers well in the documentation "How to use promises".
These updated examples are comparable. The first uses "traditional" thenable syntax. The second uses newer
async/await
syntax.You are asking two questions, one in your title and one in the body of your question.
No, but using it will change the flow of your code.
see: What is the order of execution in JavaScript promises? for a detailed explanation.
Your first example will pause execution until the promise returned by the
.then
is settled so the following will log:Your second example will make the call and then immediately continue synchronous execution with the
.then
called asynchronously after it finishes and will log:In both cases, you are using promises to handle the asynchronous operation of
f1()
, but there are some differences in how you access theresult
value. Let’s break down the two code examples:await
:In this code, you are
await
-ing the result of thef1()
function, which means that the execution of your code will pause untilf1()
completes, and theresult
will be available in thethen
callback for use insomething1(result)
..then()
withoutawait
:In this code, you are not using
await
, so the code will not pause and wait forf1()
to complete. Instead, it will continue executing, and whenf1()
finishes, thethen
callback will be invoked with theresult
. You can use theresult
value insomething2(result)
within the callback.In summary:
In the first code using
await
, the execution of your code will pause and wait forf1()
to complete, and you can useresult
within thethen
callback forsomething1
.In the second code using
.then()
withoutawait
, your code will continue executing, and whenf1()
completes, theresult
will be available in thethen
callback forsomething2
.Both approaches are valid, and which one to use depends on your specific use case and how you want to handle the asynchronous behavior in your program. If you need to ensure that
f1()
has completed before proceeding,await
is a good choice. If you want to continue with other tasks and handle the result when it’s available, using.then()
withoutawait
is appropriate.