33

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.

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.');

1
  • 3
    Why exactly do you think they should be in numerical order? 3 comes last, because that’s the last thing that gets executed after the Promise function. Do you expect 1...2...3...4. to be displayed at the very end? Then don’t use document.writeln. Use standard DOM APIs instead. Commented Apr 12, 2017 at 3:10

2 Answers 2

34

The async function will return a Promise, so you need to await the call to 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()

Sign up to request clarification or add additional context in comments.

Comments

22

You should use .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.');
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.