gpt4 book ai didi

javascript - 关于javascript异步函数的 'pending'和 'fulfilled' promise

转载 作者:行者123 更新时间:2023-11-30 20:37:16 28 4
gpt4 key购买 nike

async function pending() { 
return new Promise((resolve, reject) => { resolve(1) });
}

async function fulfilled() {
return 1;
}

function promiseState(p) {
return Promise.race([ Promise.resolve(p).then(() => "fulfilled", () => "rejected"), Promise.resolve().then(() => "pending") ]);
}

promiseState(pending()).then(s => { console.log(s); }); // pending
promiseState(fulfilled()).then(s => { console.log(s); }); // fulfilled

pending().then(r => { console.log(r); }); // 1
fulfilled().then(r => { console.log(r); }); // 1

有什么不同?

我什么时候应该在异步函数中使用'return new Promise(...'?为什么?

最佳答案

相同与不同

function pending() { 
return Promise.resolve(Promise.resolve(1));
}

function fulfilled() {
return Promise.resolve(1);
}

前者只需要一个 promise tick 就可以解决。

When should I use 'return new Promise(...' in async function?

可能永远不会。参见 How to turn this callback into a promise using async/await?What is the benefit of prepending async to a function that returns a promise? .

关于javascript - 关于javascript异步函数的 'pending'和 'fulfilled' promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49693295/

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