Javascript async / wait not working

I have a specific case where I need to wait for the result of asynchronous calls before continuing. I use the async / wait keywords, but have no luck. Any help was appreciated.

This is my attempt to try to make it 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.'); 
+5
source share
2 answers

You should use .then() after the asynchronous 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.'); }); 
+1
source

The async function will return Promise , so you need to wait for the demo call

 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() 
+4
source

Source: https://habr.com/ru/post/1266621/


All Articles