Javascript javascript异步/等待不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43359528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:51:30  来源:igfitidea点击:

javascript async/await not working

javascriptasync-await

提问by noobie

I have a specific case where I need to wait for a async calls result before continuing. I am using the async/await keywords, but not having any luck. Any help appreciated.

我有一个特定情况,我需要在继续之前等待异步调用结果。我正在使用 async/await 关键字,但没有任何运气。任何帮助表示赞赏。

This is my attempt to try getting it to work, the numbers should be in numerical order.

这是我尝试让它工作的尝试,数字应该按数字顺序排列。

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
  document.writeln('2...');
  await sleep(2000);
  document.writeln('3...');
}

document.writeln('1...');
demo();
document.writeln('4.');

采纳答案by Lee Han Kyeol

You should use .then()after async function.

您应该使用.then()after async function

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
  document.writeln('2...');
  await sleep(2000);
  document.writeln('3...');
}

document.writeln('1...');
demo().then(() => {
    document.writeln('4.');
});

回答by Danny Sullivan

The async function will return a Promise, so you need to await the call to demo

异步函数将返回 a Promise,因此您需要等待对demo

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms))

const demo = async() => {
  console.log('2...')
  await sleep(2000)
  console.log('3...')
}

const blah = async() => {
  console.log('1...')
  await demo()
  console.log('4.')
}

blah()