morsecoder
morsecoder

Reputation: 1649

Start javascript promise bluebird chain in way that handles errors

The motivation for this is to be able to catch all possible errors with the ending .catch, even ones that happen in initial synchronous code.

I want to start my promise chain like so:

const bbPromise = require('bluebird');
bbPromise.do(() => {
    someTask(); // Could throw
    return someVar.doSomeOtherTaskAsync();
})
.then((result) => {
    // Do something with result
})
.catch((err) => {
    console.log('err: ', err);
});

Is there a function that works like bbPromise.do function? bbPromise.resolve just gives me the whole lambda function that was passed in, unexecuted.

I know I could do something like this:

bbPromise.bind({}).then(() => {
    someTask(); // Could throw
    return someVar.doSomeOtherTaskAsync();
})
...

or even:

new bbPromise((resolve, reject) => {
    someTask(); // Could throw
    return someVar.doSomeOtherTaskAsync().then(resolve).catch(reject);
})
...

But these are a little indirect. Is there a good way to start a promise chain by just executing a function that could return a promise, and that has errors caught in the ending .catch?

Upvotes: 2

Views: 584

Answers (1)

ssube
ssube

Reputation: 48287

It sounds like you're looking for Promise.try. Promise.resolve is appropriate when you have a value already and want to build a promise chain from it, but if you want to run some code that may throw, use Promise.try instead.

try takes and executes a function, dealing with any synchronous exception in the same manner as then would. You would end up with something like:

bbPromise.try(someTask).then(() => {
  return someVar.doSomeOtherTaskAsync();
}).then((result) => {
  // Do something with result
}).catch((err) => {
  console.log('err: ', err);
});

Upvotes: 5

Related Questions