Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Promises confusion anti-pattern?

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 ?

like image 986
uneasy Avatar asked Aug 14 '20 08:08

uneasy


2 Answers

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

like image 101
t.niese Avatar answered Oct 12 '22 20:10

t.niese


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

like image 2
Eduard Avatar answered Oct 12 '22 19:10

Eduard