gpt4 book ai didi

Javascript:在异步函数中返回一个 promise

转载 作者:可可西里 更新时间:2023-11-01 02:11:52 26 4
gpt4 key购买 nike

如果我有,会有什么不同吗:

async function test () {
const foo = await bar()
return Promise.all([promise1, promise2])
}

代替:

async function test () {
const foo = await bar()
const [result1, result2] = await Promise.all([promise1, promise2])
// Given that I don't care about result1, result2 in this `test` function
return [result1, result2]
}

如果我这样做,我会得到相同的结果。例如。对于任何一种情况,我都可以这样做:

test().then(([result1, result2]) => { ... })

但我更好奇它们如何表现相同的底层机制。

换句话说,如果我在函数内部返回一个 promise 而不是一个值,异步函数如何处理它?<​​/p>

最佳答案

我认为您在 promise 链中使用 await 有效地调用类似同步的函数,根据此 answer :

You are perfectly free to call either synchronous functions within the promise chain (from within .then() handlers) or asynchronous functions that then return a new promise.

When you return something from a .then() handler, you can return either a value (which becomes the resolved value of the parent promise) or you can return another promise (which chains onto the previous promise) or you can throw which works like returning a rejected promise (the promise chain becomes rejected).

关于Javascript:在异步函数中返回一个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41638553/

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