Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await an asynchronous function?

My case:

let waiting = function () {
  return new Promise(resolve => {
    console.log('awaiting...');
    
    setTimeout(function () {
      resolve();
    }, 1000)
  });
};

let waitingAsync = async function () {
  console.log('start...');

  await waiting();

  console.log('stop...');
};

waitingAsync();
console.log('done...');

There are 2 things I don't understand in the code:

The first:

await waiting();

waiting is a synchronous function (because it doesn't have async keyword). So, why can I await a synchronous function?

The second:

Why couldn't done... message be awaited after completing waitingAsync function?

And main question: waitingAsync is an asynchronous function, why is await keyword not required when calling it? Just waitingAsync() instead of await waitingAsync().

If I can await waitingAsync(), done... message would be printed last.

like image 460
Tân Avatar asked Oct 25 '25 05:10

Tân


1 Answers

This isn't a function but a value that it returns which is awaited with await statement.

async and normal functions aren't different to the caller. async just returns a promise without returning it explicitly when being called. The result of waitingAsync() call is a promise. The result of waiting() call is a promise, too, so it isn't 'synchronous'.

According to the spec, both promises and non-promises can be awaited. Non-promises are converted to promises with Promise.resolve().

console.log('done...') can't be awaited because it isn't called inside async function. And it doesn't have to be awaited because it doesn't return a promise but undefined. awaiting it would be possible within async function. These await usages are equal and equally useless, all they do is 1 tick delay:

async function ... {
  ...
  await console.log('done...');
}

async function ... {
  ...
  console.log('done...');
  await undefined;
}

async function ... {
  ...
  await Promise.resolve(console.log('done...'));
}
like image 70
Estus Flask Avatar answered Oct 27 '25 17:10

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!