If I omit "await" in an async call, will the operation still complete?

Viewed 847

This is about Javascript and latest Node.JS.

I have an asynchronous operation (HTTP call via the Axios library in this particular case, but the question is in general). I don't care what the result of that operation is. If it succeeds - nice. If it fails - whatever. But I know it might take a while to complete and I cannot wait that long. So I want to "fire and forget".

Now, the first idea is simply to remove the await from the call. I'll get a Promise that I promptly forget about and the operation will complete on its own terms. I think this should work, but... feels kinda wrong. I can't put my finger on it, but it bugs me.

Is this safe, or should I better still hold on to the Promise and check its results in a timer or something, even though I won't do anything with them?

3 Answers

If you are not interested in the notification of a successful HTTP request, you still have to take into account what happens when the HTTP request fails for some reason (server not responding, no internet connection, ...).

You don't need to retain a promise object, and you don't even need async, but you should at the very least deal with a promise rejection, as otherwise you will get an "unhandled promise rejection" exception.

So do:

fetch(url).catch(err => { /* deal with error */ });

If you don't care about the error either (I doubt that), then you can just do:

fetch(url).catch(Boolean);

This way you are left with a promise that will never reject. So you can ignore it.

If I'm understanding well, then and catch are your best options:

myPromise
   .then(whatever => /* do whatever non-blocking operation you want */)
   .catch(error => /* deal with error if any */);

// you code here is not blocked by the promise

In your function, everything you wrote after the await statement will be put into a queue to execute after the asynchronous process is completed. So that way node js keep the event loop free for run any other codes.

I mean,

async function getName() {
  const name = await db.getName();
  console.log(name); // <--- this will put into a queue to execute after above line completed 
}

So technically if you don't want wait to execute console.log(name) until the above line finish, you can just remove the await keyword

function getName() {
  db.getName(); // <-- you don't even need to store it to a variable
  console.log(name);
}   

Above function is 100% synchronous. But, you have to catch the error, otherwise if it fails js throws unhandle promise rejection error. So you can easily do like below,

function getName() {
  db.getName().catch(err => undefined); // <-- you don't even need to store it to a variable
  console.log(name);   
}  

 
Related