Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.');
like image 815
noobie Avatar asked Apr 12 '17 03:04

noobie


People also ask

Can I use async await in JavaScript?

The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.

What happens when await fails JavaScript?

The await keyword before a promise makes JavaScript wait until that promise settles, and then: If it's an error, an exception is generated — same as if throw error were called at that very place. Otherwise, it returns the result.

Where is JavaScript await not valid?

The error "await is only valid in async functions and the top level bodies of modules" occurs when the await keyword is used inside of a function that was not marked as async . To solve the error, mark the directly enclosing function as async .

What happens if you don't await async in JavaScript?

In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. Code after each await expression can be thought of as existing in a . then callback.


1 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()
like image 75
Danny Sullivan Avatar answered Oct 13 '22 13:10

Danny Sullivan