Привет, ребята ~ Я нашел интересную вещь с возвращаемым значением асинхронной функции.
Есть два кода:
async function test () {
return Promise.resolve(undefined)
}
async function test () {
return undefined
}
Так в чем же разница между ними?
Если вы скажете: «Это одно и то же», как и я, то я запутался с этим кодом:
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");
});
В Chrome 73 вы получите:
async1 start
async2 start
Promise 1 start
async1 end
Then 1
Then 2
Then 3
Then 4
Теперь, если мы return Promise.resolve()
в функции async2:
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");
});
В Chrome 73 вы получите:
async1 start
async2 start
Promise 1 start
Then 1
Then 2
async1 end
Then 3
Then 4
удивительно?Обратите внимание, что async1 end
отличается от первой ситуации только потому, что мы return Promise.resolve()
в функции async2.
Кстати, код в Chrome 70 отличается от Chrome 73.
Первый в Chrome 70 вы получите
async1 start
async2 start
Promise 1 start
Then 1
Then 2
async1 end
Then 3
Then 4
А второй в Chrome 70 вы получите
async1 start
async2 start
Promise 1 start
Then 1
Then 2
Then 3
async1 end
Then 4
Разница между Chrome 70 и 73 может быть причиной в этом блоге:https://v8.dev/blog/fast-async
Так что Chrome 73, похоже, будет правильным поведением в будущем.Но я все еще в замешательстве, в чем разница между return undefined и return Promise.resolve () в асинхронной функции?