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.');
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.
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.
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 .
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With