3

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?

lcssanches
  • 995
  • 12
  • 33
  • 1
    i mean... what do you gain by doing so? You aren't taking advantage of any of the things that doing so gives you. Why is it async in the first place? – Kevin B Apr 04 '18 at 18:27
  • What if that function have to do several database modifications, and the user doesn't need to wait. It's steps, completion and errors are all logged in the database and the user can view the process accessing other web page. – lcssanches Apr 04 '18 at 19:09
  • Adding async in that case still doesn't change anything. A promise will be created and returned, then garbage collected after being unused. the function being `async` wouldn't make it faster or slower or have any impact on the code that uses it. it's entirely pointless. – Kevin B Apr 04 '18 at 19:10
  • It's not pointless. The calling function will run to completion without waiting for the `weirdFunction` call. This could make or break responsiveness if the calling function must complete as an UI related init func in a framework. Maybe you **really don't care** _when_ `wierdFunction` completes because it loads data and updates DOM and nothing else depends on it. You _should_ add a catch on the task to avoid unhandled rejections though. See [Bob Kerns answer](https://www.quora.com/How-do-you-run-an-async-function-without-waiting-for-the-result-JavaScript-async-await-development). – AnorZaken Aug 10 '21 at 13:17

1 Answers1

4

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979