Today I was asked who will return async or await first. I haven’t thought about that before, but by convention, I think who gets defined first and who gets returned first. Since await is inside async, I say async returns first.
Now it seems that although this question is correct, but did not grasp the test point.
In fact, in https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function, has a relevant description of async and await:
An async asynchronous function can contain an await instruction that suspends the execution of the asynchronous function, waits for a Promise to execute, and then continues to execute the asynchronous function and returns the result.
At first glance it looks as if await is returned first as result is returned last.
Therefore, immediately experiment with code. The effect of fetch was not obvious at first, and then manually write a Promise with a delay of 2 seconds:
const promise = () => {
return new Promise(resolve => {
console.log("promise start..");
setTimeout(() => {
resolve({ name: "tom" });
}, 2000);
});
};
const test = async () => {
try {
// const response = await fetch("./test.json");
console.log(1);
const response = await promise();
console.log(2);
console.log("response", response); } catch (error) { console.log(error); }};Copy the code
Find the output is:
1
promise start..
testPromise {<pending>} (pause 2 seconds)"tom"}
Copy the code
So async does return first, returning a Promise in a pending state. And the result is actually the last one returned, because the result is different from the Promise.
The test code is located at: codesandbox.io/s/ strang-m…