Javascript Async/Await Not Working

Javascript Async/Await Not Working

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

2 Answers

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()

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.