如何使用 setTimeout 等待延迟操作的结果?

问题描述 投票:0回答:2
function z(){
setTimeout(()=>{
        console.log("A")
    },3000)
}

z()
console.log("B")

我期望的输出

A(3 sec delay)

B

我得到的输出

B

A(3 sec delay)

如何使用此异步代码获得同步行为?

javascript async-await promise settimeout es6-promise
2个回答
0
投票

对于第一个解决方案,OP 需要......

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; }


0
投票

学习承诺后,我能够想出解决方案

'''let z=()=>{
return new Promise( (resolve,reject )=>{
    setTimeout(()=>{
        resolve (console.log("A"))
                     },3000)
    
                                    }
)
    
}

async function lol(){
 await z()
console.log("B")
}
lol()'''
© www.soinside.com 2019 - 2024. All rights reserved.