Hi guys~ I found an interesting thing with the return value of async function.
There are two codes:
async function test () {
return Promise.resolve(undefined)
}
async function test () {
return undefined
}
So what's differences between them?
If you say, 'They are the same thing' just like I did, then I'm confused with this code:
async function async1() {
console.log("async1 start");
await async2();
console.log("async1 end");
}
async function async2() {
console.log('async2 start');
// return Promise.resolve();
}
async1();
new Promise(function (resolve) {
console.log("Promise 1 start");
resolve();
}).then(function () {
console.log("Then 1");
}).then(function () {
console.log("Then 2");
}).then(function () {
console.log("Then 3");
}).then(function () {
console.log("Then 4");
});
In Chrome 73 you will get:
async1 start
async2 start
Promise 1 start
async1 end
Then 1
Then 2
Then 3
Then 4
Now if we return Promise.resolve()
in the async2 function:
async function async1() {
console.log("async1 start");
await async2();
console.log("async1 end");
}
async function async2() {
console.log('async2 start');
return Promise.resolve();
}
async1();
new Promise(function (resolve) {
console.log("Promise 1 start");
resolve();
}).then(function () {
console.log("Then 1");
}).then(function () {
console.log("Then 2");
}).then(function () {
console.log("Then 3");
}).then(function () {
console.log("Then 4");
});
In Chrome 73 you will get:
async1 start
async2 start
Promise 1 start
Then 1
Then 2
async1 end
Then 3
Then 4
amazing? Notice that, the async1 end
is different with the first situation just because we return Promise.resolve()
in async2 function.
By the way, the Code in Chrome 70 is different with Chrome 73.
The first in Chrome 70 you will get
async1 start
async2 start
Promise 1 start
Then 1
Then 2
async1 end
Then 3
Then 4
And the second in Chrome 70 you will get
async1 start
async2 start
Promise 1 start
Then 1
Then 2
Then 3
async1 end
Then 4
The difference between Chrome 70 & 73 may be the reason in this blog: https://v8.dev/blog/fast-async
So the Chrome 73 seems be the right behavior in the future. But I'm still confused, what's the differences between return undefined & return Promise.resolve() in async function?