javascript异步/等待无法正常工作

noo*_*bie 15 javascript async-await

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

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

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.');
Run Code Online (Sandbox Code Playgroud)

Dan*_*van 16

异步函数将返回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()
Run Code Online (Sandbox Code Playgroud)


Lee*_*eol 9

你应该.then()async函数之后使用.

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.');
});
Run Code Online (Sandbox Code Playgroud)