JavaScript这样的序列怎么写?

JavaScript how to write such a sequence?

我想先在 2 秒后输出一些文本,然后再输出一些“alert()”,最后仅使用 async/await 输出一些“console.log”。请帮我写这样的序列怎么写?

为什么下面的代码不起作用

async function qaz()
{
    let res1 = await setTimeout(function(){
        console.log("show me first");
    }, 2000);
    let res2 = await alert('show me second');
    let res3 = await console.log('show me at the end');
    return [res1,res2,res3];
}

setTimeoutalertconsole.log return 都不是承诺,这是一个问题,因为 await 仅适用于承诺。

不过,您仍然可以使用 async/await。创建一个 delay 函数,return 承诺您 可以 await 用于第一部分,然后在解析之后执行您的警报和日志记录。

function delay(n) {
  return new Promise(res => {
    setTimeout(() => res(), n);
  });
}

async function qaz() {
  await delay(2000);
  console.log('Show me first');
  alert('Show me second');
  console.log('Show me at the end');
}

qaz();

setTimeout 是 JavaScript 异步方法的一部分(开始执行的方法及其结果将 return 在将来的某个时间发送到称为回调队列的组件,稍后执行)

您可能想要做的是将 setTimeout 函数包装在 Promise 中并等待它,然后执行其余的同步代码。

const longTask = () => new Promise(resolve => {
      setTimeout(function(){
        console.log("show me first");
        resolve();
    }, 2000);
});
  
async function qaz()
{   
    await longTask();
    alert('show me second');
    console.log('show me at the end');
}

qaz();

我建议阅读更多关于事件循环模型的内容here