3 回答
![?](http://img1.sycdn.imooc.com/545845e900013e3e02200220-100-100.jpg)
TA贡献1936条经验 获得超6个赞
更新:在第 3 种情况下,您可以await使用async函数。
(async () => {
await wait(5000);
// Do something after 5 sec
})();
您的代码没有任何问题。所以我不确定你的问题是什么。
不管怎样,你可以这样理解Promise:
new Promise(resolve => {
setTimeout(() => {
resolve();
}, 5000);
}).then(() => {
// Do something after 5 sec
});
相当于
setTimeout(() => {
// Do something after 5 sec
}, 5000);
![?](http://img1.sycdn.imooc.com/545865b000016a9202200220-100-100.jpg)
TA贡献1909条经验 获得超7个赞
第一种情况。
1.异步执行,doSomething()不等待sleep函数完成执行。
2. 承诺将保持挂起状态。
sleep(5000);
doSomething();// execution starts without waiting for 5 seconds.
第二种情况:
1.Promise 已解决,then()/catch()侦听器被调用。
2.doSomething()执行sleep()完成后执行。
sleep(5000).then(() => {doSomething();// execution starts after waiting for 5 seconds. })
第三种情况:
1. Async 函数返回一个promise。
2. 等待/然后 - 以相同的方式工作(解决/拒绝承诺并返回数据/错误)。
3. Await 只能在 async 函数内部使用。
我建议您只创建一个包含 api 业务逻辑的异步函数。
async function wait(sleepTime) {
// some code
await sleep(sleepTime); // waiting
doSomething(); // execution starts only after waiting.
// some other code
}
调用waitwithoutthen将导致挂起的承诺,但这不会影响您的业务逻辑。
// sample example.
wait(5000).then(()=>{res.send("ok");}).catch(e=>{res.send("err")});
添加回答
举报