I spent whole day trying to figure out weather I use Promises wrongly.
Is that anti-pattern ?
export const myExample = (payload) => {
return new Promise((resolve, reject) => {})
}
Can I use async in promise like that ?
export const myExample = (payload) => {
return new Promise(async (resolve, reject) => {})
}
Also is that wrong as well ? Assuming adding async makes it a promise by default,
export const myExample = async (payload) => {
return new Promise((resolve, reject) => {})
}
also if that's the case, should I just return from function which will be same as resolve, and if I throw Error will be reject, so it would look like that ?
export const myExample = async (payload) => {
if(payload) return true
else throw new Error('Promise rejection?')
}
So is first and last the same ?
export const myExample = (payload) => {
return new Promise((resolve, reject) => {})
}
should only be used to convert code that is not promise based but returns the result asynchronously into a Promise.
export const myExample = (payload) => {
return new Promise(async (resolve, reject) => {})
}
Is an anty pattern async
already makes a function to return a Promise, and you break the promise chaining here.
export const myExample = async (payload) => {
return new Promise((resolve, reject) => {})
}
Same as the first one new Promise
should only be used to convert code that is not promise based but returns the result asynchronously into a Promise. If async
can be committed depends on the other code within that function. But it would be better that if you need to use new Promise((resolve, reject) => {})
that the enclosing function only contains and returns that new Promise
like in your first example.
also if that's the case, should I just return from function which will be same as resolve, and if I throw Error will be reject, so it would look like that ?
yes
It's a nice question, I was facing that kind of confusions as well and wanted to know where and what kind of structure to use. Came up with this:
async/await - I use it at a high level where mostly I write my handling part
async function asyncExample() {
try {
const sampleData = await otherFunction();
// You code here
} catch (err) {
// Your error handling here
}
}
It's always a good idea to use try/catch
in async/await
Using new Promise(resolve, reject) concept. I mostly use it when I have to wrap a function that only supports callbacks.
function promiseExample() {
return new Promise((resolve, reject) => {
// your code to resolve()
// otherwise to reject()
});
}
But there is a nice module promisify
which sometimes is a better solution then wrapping each function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With