When working with asynchronous JavaScript, every other function in my code looks like this:
function_name()
{
return new Promise((resolve,reject) => {
// do some async task
resolve();
});
}
Even with ES6 async
/await
I cannot avoid the part "return new Promise((resolve,reject) => { ... });
".
Is there another way of writing such code without all those duplicated lines?
First off, you should be avoiding the promise anti-pattern that wraps a new promise around other functions that already return promises. If you're doing that, then you can just stop doing that entirely and just return the promise that is already being created by your async operation. That will immediately simplify things.
If you have older style callback-based operations that are not promisified, then in general, you should promisify the base async function just once and then code only with the version of the function that returns a promise. Then, all your logic flow is using promises and you won't see the new Promise(...)
boilerplate in the regular flow of your code.
Further, you can generally avoid manually promisifying these days. If you're using node.js, then util.promisify()
can be used to create a promisified version of any async function following the node.js calling convention.
Or, if you use the Bluebird promise library, you can either promisify an individual function with Promise.promisify()
or you can promisify an entire interface with Promise.promisifyAll()
.
Using any of these alternate methods avoid the boilerplate you seem to be objecting to.
But, if you're going to manually promisify each function from scratch yourself and not use any of these other helper functions, then there is no way to avoid the new Promise(...)
syntax. That's what it takes.
So, most of your coding should NOT involve new Promise(...)
. If it does, then you need to show us some of your examples and we can advise, better/different ways to code.