我有一个我在一个例子中找到的代码,它都是快捷方式:
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毫秒后解析的承诺。您可以将其视为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;
}
如果你想有条件地解决诺言并做一些计算,你可以在setTimeout函数中做到这一点:
await new Promise(resolve =>
setTimeout(()=>{
if('Some consition'){
resolve('some value')
}
else{
resolve('some other value')
}
}, 2000)
)