0

I have next doubt, I was practicing about async/await functions stuff. I have created a simple test:

console.log('Testing async-await');

main();

async function wait(nSeconds) {
  await setTimeout(function() {
    console.log('Request finished !!');
  }, nSeconds * 1000);
}
async function main() {
  let a = await wait(5);
  console.log('end !!');

}

My idea, as long as I understand is simulate with wait(nSecond) function a waiting like a ajax request, for example. Everithing is called in main() function.

My actual output is :

enter image description here

But... souldnt be ??? :

Testing async-await
Request finished !!
end !!

Im telling to my code, when you get on line 'let a = await wait(5);' just dont continue until end of function is resolved . So what is happening here.

Barmar
  • 741,623
  • 53
  • 500
  • 612
josanangel
  • 130
  • 1
  • 5

1 Answers1

1

The function wait should look like this:

function wait(nSeconds){
    return new Promise( resolve => setTimeout( resolve, nSeconds * 1000 ) )
}

The setTimeout method does not return promise so await keyword does not work in this case.