我在Promise上有代码:
function one() {
return new Promise((rs,er)=>{
console.log('start');
new Promise((rr,err)=>{setTimeout(()=>{console.log('after 3 sec');rr()},3000)})
.then( sd => {
console.log('endLong');
rs();
})
});
}
one().then(_ => one()).then(_ => one());
结果我获得了同步代码。
但是当我将它重构为async / wait
时async function one() {
console.log('start');
await longtime();
console.log('endLong');
}
async function longtime() {setTimeout(()=>{console.log('after 3 sec');},3000);}
one().then(_ => one()).then(_ => one())
然后我得到了:
start
endLong
start
endLong
start
endLong
Promise {<resolved>: undefined}
after 3 sec
after 3 sec
after 3 sec
怎么了?
答案 0 :(得分:1)
您需要A#getStuff()
才能返回承诺。单独使用longtime
并不意味着基于承诺setTimeout
/ async
:
await
答案 1 :(得分:0)
setTimeout
不会返回承诺。异步函数应该返回一个使用值解析的promise。
function longtime() {
return new Promise(resolve => {
setTimeout(() => {
console.log('after 3 sec');
resolve();
}, 3000);
});