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;
}
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;
}
Share
Improve this question
edited Aug 9, 2021 at 14:14
Mehdi
asked Aug 9, 2021 at 14:06
MehdiMehdi
1,1464 gold badges16 silver badges28 bronze badges
1
- 3 JS doesn't "manage" async functions (unfortunately), so they just run and return a promise. If you ignore the promise, that's your fault, and rejections will go unhandled. – Bergi Commented Aug 9, 2021 at 14:09
2 Answers
Reset to default 7It'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).
It's true for javascript as well.
You don't want to just create a promise and leave it totally hanging, if there are errors then they bee unhandled errors and if it exits unexpectedly then you have no way of knowing that.
What I remend is using the Promise.race
at the top level and then it will run all of your async functions in parallel but will exit if any one of them exits unexpectedly.
async function worker() {
while (true) {
// do background work in a loop
}
}
async function server() {
await init()
await listen()
}
function main() {
const p0 = worker()
const p1 = server()
try {
await Promise.race([p0, p1])
console.log('done')
return true
} catch (err) {
console.log('The server had an error unexpectedly', err)
return false
}
}
If you expect the promises to eventually exit gracefully then use Promise.all
instead, which will wait until all promises exit successfully before resolving.