function z(){
setTimeout(()=>{
console.log("A")
},3000)
}
z()
console.log("B")
我期望的输出
A(3 sec delay)
B
我得到的输出
B
A(3 sec delay)
如何使用此异步代码获得同步行为?
对于第一个解决方案,OP 需要......
wait
函数,它接受一个数值(代表毫秒)并返回一个 Promise
实例,该实例在提供的延迟后解决。wait
方法记录等待时间后要延迟的值,从而利用
then
函数。function wait(msec) {
return new Promise(resolve =>
setTimeout(resolve, msec)
);
}
console.log('A');
wait(3000)
.then(() => console.log('B'));
.as-console-wrapper { min-height: 100%!important; top: 0; }
async function
,它会记录两个 OP 的值,并在记录之间记录 await
wait
返回的承诺。
function wait(msec) {
return new Promise(resolve =>
setTimeout(resolve, msec)
);
}
(async () => {
console.log('A');
await wait(3000);
console.log('B');
})();
.as-console-wrapper { min-height: 100%!important; top: 0; }
学习承诺后,我能够想出解决方案
'''let z=()=>{
return new Promise( (resolve,reject )=>{
setTimeout(()=>{
resolve (console.log("A"))
},3000)
}
)
}
async function lol(){
await z()
console.log("B")
}
lol()'''