-1

I have the following code:

function one() {

    setTimeout(() => {

        console.log('one');
    }, 2000);
}

function two() {
    console.log('two');
}

function three() {
    console.log('three');
}

function wrapper() {
    one();
    two();
    three();
}

wrapper();

This of course console logs them in the following order: two three one

Using async / await I'd like to console log them in the following order: one two three

I'm not sure how to achieve this.

Thanks

Daniel Lizik
  • 3,058
  • 2
  • 20
  • 42
Behzad Lashkari
  • 177
  • 1
  • 9
  • 1
    Possible duplicate of [Combination of async function + await + setTimeout](https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout) – Ivar Nov 21 '19 at 09:02
  • it's already implemented in most browsers https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function. if you want old IE support you need babel/webpack – Daniel Lizik Nov 21 '19 at 09:05
  • Just wondering why my question was down voted? – Behzad Lashkari Nov 21 '19 at 10:16

2 Answers2

2

You have to make use of async and Promises. Please have a look at the documentation.

The code below returns a Promise call. The Promise itself sets a timeout of two seconds and after this time it logs "one" to the console.

You can wait for the promise to finish using the await-keyword right before the function call.

Note that the functions have to be async.

 return new Promise((resolve)=>{
    setTimeout(() => {
        console.log('one');
        resolve();
      }, 2000);
  })

Heres a updated version of your code - I hope this helps:

async function one() {
  return new Promise((resolve)=>{
    setTimeout(() => {
        console.log('one');
        resolve();
      }, 2000);
  })
}

async function two() {
  console.log('two');
}

async function three() {
  console.log('three');
}

async function wrapper() {
  await one();
  await two();
  await three();
}

wrapper();
1

async function one(){ 
  await new Promise(resolve => 
  setTimeout(async () => {
     await resolve(console.log('one'));
    }, 2000));
 
}

function two() {
    console.log('two');
}

function three() {
    console.log('three');
}
async function wrapper(){ await one(); two(); three();}

wrapper();
Nakarmi
  • 453
  • 1
  • 6
  • 16
  • Why do we need setTimeout. This will just delay the output and "one" will never be populated first. Let's focus on the required output. – Nakarmi Nov 21 '19 at 09:33
  • Ok, so I've edited by applying the setTimeout. Does this satisfy the query. – Nakarmi Nov 21 '19 at 09:59
  • 1
    Thanks for the update. As far as I can tell this is exactly what OP is after. I've retracted my downvote. One last remark: it is always recommended to add an explanation of what changes you made so OP and future visitors can learn from it/know how to apply it themselves. – Ivar Nov 21 '19 at 10:06