Can I fire and forget a promise in nodejs (ES7)?

arisalexis picture arisalexis · Sep 3, 2015 · Viewed 12.1k times · Source

I would like to run this code with babel:

redisClientAsync.delAsync('key');
return await someOtherAsyncFunction();

inside an async function without await the first line. is this OK?

how else can I run something that I don't care?

Can I just fire the non-promisified function del('key',null) without a callback?

Answer

Bergi picture Bergi · Sep 3, 2015

Yes, you can do that, and it will run the two asynchronous functions in parallel. You've just created a promise and thrown it away.

However, this means that when the promise is rejected you won't notice. You'll just get an unhandledRejection eventually which will crash your process if not handled.

Is this OK? How can I run something that I don't care?

Probably it's not OK. If you truly wouldn't care, you hadn't run it in the first place. So you should be clear and explicit what you care about (and what not):

  • do you want to wait? (for side effects)
  • do you need the result?
  • do you want to catch exceptions?

If you only want to wait and don't care for the result value, you can easily throw away the result:

void (await someAsyncFunction()); // or omit the void keyword,
                                  // doesn't make a difference in an expression statement

If you don't care about exceptions, you can ignore them using

… someAsyncFunction().catch(function ignore() {}) …

You can throw that away, await it, do anything with it.

If you want the result, you have to await it. If you care about exceptions, but don't really want to wait, you may want to execute it in parallel with the following functions:

var [_, res] = await Promise.all([
    someAsyncFunction(), // result is ignored, exceptions aren't
    someOtherAsyncFunction()
]);
return res;