Skip to content

What if we do not wait for an asynchronous javascript function?

What if we do not wait for an asynchronous javascript function?

As far as I know some languages like C # should not run an asynchronous function unmanaged!

I wanted to know if this is also true for the JavaScript language?

var asynchronousFunction = async function() {
    //...
}

function main() {
   var result = true;
   //...
   asynchronousFunction(); // The result of this function has no effect on our output (result)
   //...
   return result;
}

Answer

It’s run just the same. (In fact, you never await a function, you await for the the Promise it returns.)

The asynchronous function is run synchronously until the first await or return within it, at which point a Promise is returned to the caller and the rest of the function is arranged to run later.

It’s up to the caller to do something (or nothing) to the Promise. After all, you might wish to store the promise in an array and await for the lot of them (Promise.all) or do something more esoteric about it, so JavaScript itself doesn’t care.

Some smart enough IDEs and linters are able to raise a warning about unhandled promises, though, especially if you have enough type information to do so (e.g. by using TypeScript).