1

I am trying to understand the asnyc await functionality. Therefore, i want to use an asnyc function, resolve it and do the following logs sequentially afterwards.

How do I achieve this? Or am I understanding something fundamentally wrong?

const test = async function() {
    console.log('hi 1');
    await setTimeout(() => {
        console.log('timout1')
    }, 1000);
    console.log('hi 2');
    console.log('hi 3');
}
test()

Result

hi 1
hi 2
hi 3
timout1

Expected Result

hi 1
timout1
hi 2
hi 3
Jimbo.Koen
  • 151
  • 10

2 Answers2

1

You can use await for promises only and the setTimeout function doesn't return a Promise. However you can await a Promise that is resolved using setTimeout like so which will give you the desired result.

So, the function execution will halt untill either the Promise being awaited gets resolved or gets rejected and then continue.

const test = async function() {
  console.log('hi 1');
         // return a new promise resolved after setTimeout callback is fired
  await (new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('timout1')
      resolve()
    }, 1000)
  }))
  console.log('hi 2');
  console.log('hi 3');
}

test()

Hope this helps !

Hemant Parashar
  • 3,684
  • 2
  • 16
  • 23
1

I hope this code help you to understand async await.

function resolveAfter2Seconds() {
   return new Promise(resolve => {
     setTimeout(() => {
        resolve('resolved');
     }, 2000);
   });
}

async function asyncCall() {
   console.log('hi 1');
   const result = await resolveAfter2Seconds();
   console.log(result);
   console.log('hi 2');
   console.log('hi 3');
}

asyncCall();
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35