如果使用 await,setTimeout 的同步使用会停止代码吗?

Wha does synchronous usage of setTimeout stops the code if using await?

下面的代码带来的只是 "before timeout" 和 "within" 但不是 "after timeout"。 这是为什么?

async function asy() {
   console.log('before timeout');
   await awa();
   console.log('after timeout');
}

async function awa() {
   return new Promise(resolve => {setTimeout(function(){console.log('within');}, 600);
}

asy();

因为你永远不会解决承诺,所以它永远挂着。

return new Promise(resolve => {setTimeout(function(){console.log('within');}, 600);
                   ^^^^^^^
                  NEVER USED

返回后您还没有解决 Promise,因此输出

async function asy() {
   console.log('before timeout');
   await awa();
   console.log('after timeout');
}

async function awa() {
   return new Promise(resolve => {
        setTimeout(function(){
           console.log('within');
           resolve();
   }, 600);
}

asy();

await 等到 Promiseresolvedrejected 后再执行以下表达式

你不需要函数 awa() 之前的异步:

async function asy() {
    console.log('before timeout');
    await awa();
    console.log('after timeout');
}

function awa() {
  return new Promise(
    resolve => {
        setTimeout(function(){console.log('within'); resolve();}, 600);
    });
}

asy();

兑现承诺

   this.driverWait = async function (explicitWaitMS) {
        // create a new promise inside of the async function
        let promise = new Promise((resolve, reject) => {
            setTimeout(() => resolve(true), explicitWaitMS) // resolve
        });

        // wait for the promise to resolve
        await promise;
    }