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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like