Yashua Yashua - 4 months ago 16
Javascript Question

Is wrapping a promise in a try/catch block the proper method?

I have a function that calls a promise. On success or failure I would like to return some data beyond what the promise returns.

I thought this might work:

function foo() {
const extra = 'bar'
return thepromise().then((res) => {
return {
result: res,
data: extra
}
}, (err) => {
// this will not happen if an error is thrown in the called promise
return {
result: res,
data: extra
}
})
}

foo().then((res) => { }, (err) => { // error result ends up here })


However this does not work. if an error is thrown in the
thepromise
it will not call the catch block but instead the catch block of
foo()
.

What is the proper way to handle this? I am successful with a try/catch block but I am not sure this is the best approach:

function foo() {
const extra = 'bar'
return new Promise((resolve, reject) => {
try {
return thepromise(p)
} catch (e) {
reject(e)
}
})
.then(function(res) {
return {
result: res,
data: extra,
status: 'success'
}
}, function(err) {
return {
result: err,
data: extra
status: 'error'
}
})
}

Answer

If you're willing to entertain extensions to Promises, bluebird has a try method that does just what you need:

import Promise from 'bluebird';

// ...

return Promise
  .try(thepromise)
  .then(res => ({
    result: res,
    data: extra
  })
  .catch(err => ({
    result: res,
    data: extra
  });