0

I am facing an issue while using async-await function in javascript.Let's have a look my code first.

function take() {
  setTimeout(() => {
    console.log('take order');
  }, 4000);
}

function complete() {
  setTimeout(() => {
    console.log('complete order');
  }, 20);
}

async function processOrder() {
  let a = await take();
  let b = await complete();
}

processOrder();

In the code above,I used await to control the order of the tasks.But it didn'twork.The complete function exicuted before the taks function.But I used await to wait in the task function to exicute and then the complete function exicution.

This is not a real life issue.I wonder what is going on here.Can anyone please explain it to me?

  • 2
    `await` should be used on Promises. Your functions should each return a Promise that resolve after the set amount of milliseconds. – Nick Parsons Apr 17 '21 at 04:53
  • See: [What is the JavaScript version of sleep()?](https://stackoverflow.com/a/39914235) – Nick Parsons Apr 17 '21 at 04:54
  • You are awaiting two functions that are both NOT defined as async, nor is some async job to do inside. So async has no effect on them. Just adding "await" in front of a function does not make it asynchronous: it must be some asynchronous job inside, like a promise. And you should set async function take() , and async function complete() – Don Diego Apr 17 '21 at 08:14

1 Answers1

3

your functions are not using promise that's why it doesn't work!

function take() {
  return new Promise(resolve => {
    setTimeout(() => {
       console.log('take order');
       resolve()
    }, 4000);
  })
  
}