Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/Await code not being executes after await

I have been going over async/await. I trying few simple examples but unable to understand flow of async and await . In below code

function wait(ms) {
  return new Promise(r => setTimeout(function() {
    console.log('Hello');
  }, ms));
}

async function GetUser() {
  await wait(5000);
  console.log('world');
}

GetUser();

Why is the message "world" not logged? Only "Hello" prints.

like image 721
Siva Avatar asked Oct 30 '25 21:10

Siva


1 Answers

You should call the resolver.

function wait(ms) { 
 return new Promise(r => setTimeout(function(){console.log('Hello'); r();}, 
//                                                                   ^^^ this
ms));
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

like image 194
Nurbol Alpysbayev Avatar answered Nov 02 '25 11:11

Nurbol Alpysbayev