gpt4 book ai didi

javascript - 异步和 promise 从快捷方式更改

转载 作者:行者123 更新时间:2023-12-02 23:45:38 24 4
gpt4 key购买 nike

我在示例中找到了这段代码,它们都在快捷方式中:

async function test1(){
const p = await new Promise(resolve => setTimeout(resolve, 2000)).then(()=>'test1');
console.log('Completed test1');
return p;
}

我想删除 setTimeout 并将其放在非快捷方式中,这样我就可以向其中添加多个命令并执行除超时之外的其他操作...

例如:

async function test1(){
const p = await new Promise(resolve => setTimeout(resolve) => {
// line here
// another one etc
}

如何更改上面的代码?

最佳答案

async function test1(){
const p = await new Promise(resolve => setTimeout(resolve, 2000)).then(()=>'test1');
console.log('Completed test1');
return p;
}

我认为你还没有完全理解这段代码。 setTimeout 不是快捷方式。 new Promise(resolve => setTimeout(resolve, 2000)) 用于创建一个将在 2000 毫秒后解析的 Promise。您可以将其视为一个 API 调用,它将在 2000ms 后调用回调

让我们破解这段代码:

// A function test1 which is defined async sow you can use await inside it
async function test1(){
// You can await for promises.
// As explained await new Promise(resolve => setTimeout(resolve, 2000))
// is just a promise resolving after 2000ms
const p = await new Promise(resolve => setTimeout(resolve, 2000))
// .then block will run after promise gets resolved
// p will bcome test1
.then(()=>'test1');
console.log('Completed test1');
return p;
}

如果您想有条件地解决 promise 并进行一些计算,您可以在 setTimeout 函数中执行此操作:

await new Promise(resolve => 
setTimeout(()=>{
if('Some consition'){
resolve('some value')
}
else{
resolve('some other value')
}
}, 2000)
)

关于javascript - 异步和 promise 从快捷方式更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55866764/

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