Silver
Silver

Reputation: 5091

Catching Errors from Promise construction

Is there a better way of doing the following using Bluebird promises

Promise.resolve()
    .then(function() {return new MyObject(data)})
    .then.....etc
    .catch(function (e){ //handle it}) 

I have MyObject - and data passed in from an external system, which could be invalid, thus could break the promise chain. Wrapping the object creation in a function in a then seems really messy tho. Is there something like

Promise.something(new MyObject(data))
       .then()....
       .catch....

Also - Node 0.10 so no Lambda to make it look tidier :-(

Upvotes: 0

Views: 45

Answers (2)

ssube
ssube

Reputation: 48277

Rather than Promise.something(new MyObject(data)), which runs new MyObject before creating the Promise, use the long-form promise constructor:

new Promise(function (resolve) {
  resolve(new MyObject(data));
}.then(foo).catch(bar);

Exceptions thrown synchronously within a promise constructor or then callback will be caught, processed (including type matching), and sent on to catch handlers (Bluebird docs).

Upvotes: 2

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276366

Sure there is, Promise.try, also you should be using arrows for short function expressions in Node:

Promise.try(() => new MyObject(data));

Like in browsers, you can use a transpiler for old versions of Node.

Also, I would not perform IO in a constructor but that's another story. The other answer by ssube explains why a constructor is needed because exceptions occur before the method is actually called.

Upvotes: 0

Related Questions