Can I run and forget the promise in nodejs (ES7)?

I would like to run this code with babel:

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

inside an asynchronous function without waiting for the first line. this is normal?

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

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

+3
javascript promise es6-promise ecmascript-7 async-await
source share
2 answers

Yes, you can do this, and it will run two asynchronous functions in parallel. You just made a promise and threw it away.

However, this means that when the promise is rejected, you will not notice. You just get unhandledRejection in the end .

This is normal? How can I run something that I don't care?

Perhaps this is not OK. If you really do not care, you did not run it in the first place. Therefore, you must be clear and clear about what you care about (and what not):

  • Do you want to wait? (for side effects)
  • Do you need a result?
  • Do you want to catch exceptions?

If you only want to wait and not care about the meaning of the result, you can easily discard 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 it away, wait, do something with it.

If you want to get a result, you have to wait for it. If you are worried about exceptions but don’t want to wait, you can run it in parallel with the following functions:

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

inside an asynchronous function without waiting for the first line. this is normal?

Yes, there are times when you want to do this, which is quite reasonable. Especially where you do not care about the result - one example is the analytics tracking operation, which should not interfere with a critical business code.

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

In many ways, however, just calling the promise function works. Your del without a callback will probably work in this case, but some functions do not protect against callback transitions, so instead you can pass an empty function ( .del('key', () => {}) ).

However, you want you to be aware of this failure even if you do not want to disrupt the code, so please consider adding a process.on("unhandledRejection', event handler to explicitly ignore these specific exceptions or suppress them with:

 redisClient.delAsync('key').catch(()=>{}); 

Or, preferably something like:

 redisClient.delAsync('key').catch(logErr); 
+1
source share

All Articles