与某人讨论并遇到这种奇怪之处:</ p>
const wait = async () => new Promise(resolve => setTimeout(resolve, 1000));
async function case1() {
const {a, b} = {a: await wait(), b: await wait()};
return {a, b};
}
async function case2() {
return {a: await wait(), b: await wait()};
}
async function case3() {
const {a, b} = {a: wait(), b: wait()};
return {a: await a, b: await b};
}
async function case4() {
const {a, b} = {a: wait(), b: wait()};
const {c, d} = {c: await a, d: await b};
return {c, d};
}
function test() {
const start = new Date();
case1().then(() => console.log('case1:', +new Date() - start));
case2().then(() => console.log('case2:', +new Date() - start));
case3().then(() => console.log('case3:', +new Date() - start));
case4().then(() => console.log('case4:', +new Date() - start));
}
case1
和case2
都会在2秒内完成。 case3
和case4
在1秒内完成。
是否存在一些奇怪的隐式Promise.all
或其他东西?
答案 0 :(得分:0)
您在wait()
和await
处不使用case3
来调用函数case4
。差别就是这样。
答案 1 :(得分:0)
在#3情况下,立即调用wait()
函数,因此只有1秒的超时(对于它们两者),而在另外两个(情况#1和情况#2)中{{1} 1}}将“做它的工作”并等待异步调用返回。
正如您在此处所见,两个呼叫都会立即调用await
。
console.log(Date())
此处正在使用const wait = async () => new Promise(resolve => console.log(Date()) || setTimeout(resolve, 1000));
async function case3() {
const {a, b} = {a: wait(), b: wait()};
return {a: await a, b: await b};
}
function test() {
const start = new Date();
case3().then(() => console.log('case3:', +new Date() - start));
}
test();
:
await