Promise.

I looked at bluebird promises and as promised. different than the promise. Solved. Then an error occurs. First, some code using prom.try, where it generates a synchronous error

Promise.try(function() { throw new Error('error'); }).catch(function(e) { console.log(e); }); 

second code that causes a synchronous error when resolving

 Promise.resolve().then(function() { throw new Error('error'); }).catch(function(e) { console.log(e); }); 

As far as I know, they both behave the same. Did he promise, in fact, a cleaner way to deliver on this promise?

The docs say prom.try:

will catch all errors in its Promise.catch handlers instead of handling synchronous and asynchronous exception flows.

In the case of the example given in the docs:

 function getUserById(id) { return Promise.try(function() { if (typeof id !== "number") { throw new Error("id must be a number"); } return db.getUserById(id); }); } 

if a synchronous error is selected, the asynchronous code will never be reached. Will there be any difference if you put the code above in the promise .resolve (), then (..)?

Any clarification / examples of prom.try would be much appreciated.

+7
promise bluebird
source share
2 answers

Adding Bergi to the answer: Promise.try for those cases when you cannot use Promise.method . The goal is to avoid cases where you have synchronization exceptions mixed with deviations.

Generally, whenever you plan to use Promise.try , give Promise.method spin.

 var fn = Promise.method(function(){ // can throw or return here, and it'll behave correctly }); 

About the same:

 var fn = function(){ return Promise.try(function(){ // can throw or return here, and it'll behave correctly }); }); 
+10
source share

As far as I know, they both behave the same.

Yes, basically. However, the .then(…) callback will be called asynchronously, and Promise.try will execute your function synchronously.

Is a promise a cleaner way to resolve a promise?

Yes, this provides a cleaner (less messy) notation. But this is more of an optimization, because it does not create Promise.resolve(undefined) .

+6
source share

All Articles