【发布时间】:2018-12-12 12:14:30
【问题描述】:
大家好~我发现异步函数的返回值很有趣。
有两个代码:
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
现在如果我们在 async2 函数中return Promise.resolve():
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 与第一种情况不同,只是因为我们在 async2 函数中 return Promise.resolve()。
顺便说一句,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() 有什么区别?
【问题讨论】:
-
如果您想获得更多的乐趣,请将
async从async2()函数中不返回承诺(你的第一个例子)。 -
除非我遗漏了什么,如果它是异步的,这不只是由于性质吗?
-
“那么它们之间有什么区别呢?” ???? explicit promise creation anti-pattern。 TL;DR -
return ...解析异步函数返回值(一个承诺)。return Promise.resolve(...)做同样的事情,只是它用另一个本身立即解决的承诺来解决 -
@Phil 如果是这样,
return Promise.resolve()将比return undefined更快。而结果恰恰相反
标签: javascript promise async-await