Refer to the article: jakearchibald.com/2017/await-…
primers
I am surprised to see the following two expressions. What is the difference between them? The following article is a super detailed introduction of “await return” and “return await”.
const connection = await createConnection()
return connection
// and
return await createConnection()
Copy the code
start
When writing asynchronous functions, it is very easy to get await, return, return await. It is very important to write the right one.
We’ll start by defining an asynchronous function waitAndMaybeReject that has a 50/50 chance of success — returning ‘yay’ — and a 50/50 chance of throwing an Error — Error(‘Boo! ‘)
async function waitAndMaybeReject() {
// Execution takes one second
await new Promise(r= > setTimeout(r, 1000));
/ / flip a coin
const isHeads = Boolean(Math.round(Math.random()));
if (isHeads) return 'yay'; // Half are successful
throw Error('Boo! '); // Half throw an error
}
Copy the code
Here’s an overview of the results:
Next, we will analyze the following several cases: the key is abnormal case oh!
Knowledge review
What you need to know:
await foo()
async function foo() {
await waitAndMaybeReject();
}
Copy the code
When await waitAndMaybeReject (); Execution time:
- Await suspends the current function
foo
, waiting for the promise processing to complete; - If the promise is fulfilled normally, the resolve parameter of its callback will be treated as the value of the await expression and execution will continue
async function foo
; - If a promise exception (Rejected), await will throw the exception reason;
- Also, if the expression after the await operator is not a promise, the value itself is returned.
There is no await
async function foo1() {
try {
waitAndMaybeReject();
}
catch (e) {
return 'caught'; }}Copy the code
Result: Return undefined immediately.
Analysis: When executing foo1, since waitAndMaybeReject is an asynchronous function, try… Catch can only catch synchronous errors, so nothing happens and undefined is returned.
await
async function foo2() {
try {
await waitAndMaybeReject();
}
catch (e) {
return 'caught'; }}Copy the code
Error case diagram:
Results:
- Results return 1 second later;
- Return undefined if waitAndMaybeReject succeeds;
- WaitAndMaybeReject fails, return ‘caught’. [Exception caught]
Analysis:
- Await and async together, is a serial asynchronous function;
- When waitAndMaybeReject succeeds, only the try block region is executed, and since no value is returned, undefined is returned by default;
- When waitAndMaybeReject fails, an error is thrown, and the catch block catches the error and returns ‘caught’.
return
async function foo3() {
try {
return waitAndMaybeReject();
}
catch (e) {
return 'caught';
}
console.log(4); // Will not be executed
}
Copy the code
Because I’m going to take the delta functionwaitAndMaybeReject
returnOut, so the rest will not be executed! (for example, console.log(4) above)
Error case diagram:
Results:
- Results return 1 second later;
- Return ‘yay’ when waitAndMaybeReject succeeds
foo3
End of execution; - When waitAndMaybeReject fails, the Error Error(‘Boo! ‘), function
foo3
Execution terminated.[Exception not caught]
Analysis:
- Await and async together, is a serial asynchronous function;
- When waitAndMaybeReject succeeds, only the try block is executed, and return gets ‘yay’, so ‘yay’ is returned;
- When waitAndMaybeReject fails,
Return catches the thrown error, the function is terminated, and the catch block area does not catch the error
.
return await
async function foo4() {
try {
return await waitAndMaybeReject();
}
catch (e) {
return 'caught'; }}Copy the code
Results:
- Results return 1 second later;
- Return ‘yay’ when waitAndMaybeReject succeeds;
- WaitAndMaybeReject fails, return ‘caught’.
The above code can be viewed as the following, and it makes sense:
async function foo4_() {
try {
const fulfilledValue = await waitAndMaybeReject();
return fulfilledValue;
}
catch (e) {
return 'caught'; }}Copy the code
Analysis:
- Await and async together, is a serial asynchronous function;
- When waitAndMaybeReject succeeds, only the try block region is executed, and ledValue is ‘yay’, so ‘yay’ is eventually returned;
- When waitAndMaybeReject fails, the ledValue of the try block gets the error thrown, the catch catches the error, and finally returns ‘caught’. [Exception caught]
Return await only in try… Catch, otherwise esLint will report redundancy.
See: eslint
Respond to the beginning
So these two notations mentioned at the beginning, the latter is actually the abbreviation of the former !!!! Wow!!!!!!
const connection = await createConnection()
return connection
// and
return await createConnection()
Copy the code
Code duplication
The following code is the test code of the article, which can be copied and executed directly:
async function waitAndMaybeReject() {
// Wait one second
await new Promise(r= > setTimeout(r, 1000));
// Toss a coin
const isHeads = Boolean(Math.round(Math.random()));
if (isHeads) return 'yay';
throw Error('Boo! ');
}
async function foo1() {
try {
waitAndMaybeReject();
}
catch (e) {
return 'caught'; }}async function foo2() {
try {
await waitAndMaybeReject();
}
catch (e) {
return 'caught'; }}async function foo3() {
try {
return waitAndMaybeReject();
}
catch (e) {
return 'caught'; }}async function foo4() {
try {
return await waitAndMaybeReject();
}
catch (e) {
return 'caught'; }}var test = async() = > {console.log('pare')
console.log(await foo1())
console.log('await')
console.log(await foo2())
console.log('return')
console.log(await foo3())
console.log('return await')
console.log(await foo4())
}
test()
Copy the code