gpt4 book ai didi

javascript - 等待异步函数

转载 作者:行者123 更新时间:2023-12-01 03:29:27 25 4
gpt4 key购买 nike

有没有办法等待异步函数?像 yield* (带有星号)这样的东西将委托(delegate)给另一个生成器函数。

例如:

asyncFunction1 = async () => {
await promise1;
await promise2;
}

asyncFunction2 = async () => {
await asyncFunction1(); // can we do that or it MUST be a promise?
}

最佳答案

标记函数async使其隐式返回一个promise:

When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.

( source )

换句话说,您可以在异步函数上 await,即使该函数返回非 Promise 值(因为该值将自动用 Promise 包装):

async function test() {
return 123;
}

void async function() {
let value = await test();
console.log('value', value);
}();

关于javascript - 等待异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44617613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com