then / promise

Bare bones Promises/A+ implementation
https://www.promisejs.org
MIT License
2.58k stars 312 forks source link

Add an additional method #145

Closed BlackHole1 closed 6 years ago

BlackHole1 commented 6 years ago

Promise lacks an unified operation method

Core:

Promise.prototype.unified = function (callback) {
  this.then(
    data => {callback(true, data)},
    data => {callback(false, data)}
  )
}

Use:

let promise = new Promise(function(resolve, reject) {
  if (false){
    setTimeout(() => resolve('success'), 1000)
  } else {
    setTimeout(() => reject('error'), 1000)
  }
})

promise.unified((state, data) => {
  const msg = state ? 'operation successful' : 'operation failed'
  console.log(
    state,
    data,
    msg
  )
})

If it was before, then it should be done:

let promise = new Promise(function(resolve, reject) {
  if (false){
    setTimeout(() => resolve('success'), 1000)
  } else {
    setTimeout(() => reject('error'), 1000)
  }
})

promise.then((data) => {
  console.log(
    state: true,
    data: data,
    msg: 'operation successful'
  )
}).catch((data) => {
  console.log(
    state: false,
    data: data,
    msg: 'operation failed'
  )
})

It is less coordinated to do this, I think it would be better to add the unified method

BlackHole1 commented 6 years ago

if resolve and reject handle almost the same. I think this is very necessary. Because it can simplify a lot of unnecessary code.

Translation for Google. It may not be very well worded. Please forgive me.

ForbesLindesay commented 6 years ago

I do think this is an interesting use case. We need a very good reason for adding additional non-standard methods though, and I don't think this is a sufficiently large problem that we should include another non-stanadard method in this implementation.

A workaround like this seems good enough to me:

promise.then(
  data => ({state: true, data}),
  data => ({state: false, data}),
).then(({state, data}) => {
  const msg = state ? 'operation successful' : 'operation failed'
  console.log(
    state,
    data,
    msg
  )
})
BlackHole1 commented 6 years ago

I wrote a package to enhance Promise

https://www.npmjs.com/package/promise-unified

Can you add this description to the README.md? Because I think some people will use this method. I think it's not very intuitive to add the then method on the basis of the original.