lcssanches
lcssanches

Reputation: 1014

Down-side on calling async function without await

Given the code with async

async function wierdFunction(){
    setTimeout(function(){
        //background process that does not return
        //Russian roulette
        if ( Math.random() > 0.99 )
            throw new Error('Bang!');
    }, 3000);
}

I only need to call this function asynchronous, I don't need to know when it finished.

app.post('/wierd-endpoint', function (req,res){
    wierdFunction();
    res.json({status:"Running. Now, go away."});
});

Is there any advise against calling it without await keyword?

Upvotes: 5

Views: 5522

Answers (1)

jfriend00
jfriend00

Reputation: 708206

Just remove the async from wierdFunction(). If you're not using the returned promise and not using await inside, then there's no reason to have it. It just creates an extra promise object for the return that then gets garbage collected so it creates extra overhead and it implies to the caller that the caller can use that promise for something useful.

Is there any advise against calling it without await keyword?

If your operation is truly "fire and forget" and you don't care about completion or reported errors, then it does not need to return a promise and you can just make it a normal function that initiates an asynchronous operation, but doesn't report any results.

But, you do have to make absolutely sure that a rejected promise never goes unhandled because that may cause nodejs to shutdown. So, even a fire and forget scenario needs to make sure that any errors that can occur are handled somewhere.

Upvotes: 6

Related Questions