Bluebird.JS Promise: new Promise(function (resolve, reject){}) vs Promise.try(function(){})

后端 未结 3 647
刺人心
刺人心 2020-12-19 12:02

When should I use which? Are the following the same?

new Promise() example:

function multiRejectExample(){ 
  return new Promise(function (resolve, r         


        
3条回答
  •  暖寄归人
    2020-12-19 12:42

    Are the following the same?

    No. As @robertklep already mentioned, they do have different results when statement is false. Promise.try catches exceptions and otherwise resolves with the return value from the function, while the Promise constructor just creates a new promise and doesn't care when it is never resolve()d.

    When should I use which?

    You should use the Promise constructor iff, and really only if, you are promisifying an asynchronous callback API. Everything else, especially when involving other promises, is basically an antipattern.
    So don't use it like you have in your question.

    You usually don't throw either. You're writing a function that returns a promise (because it is asynchronous), and it should always return a promise. If you want to return a promise that is rejected with an error, you can create one explicitly by using Promise.reject. The proper approach would therefore be

    function multiRejectExample(){ 
        if (statement){
            console.log('statement 1');
            return Promise.reject(new Error('error'));
        }
        if (statement){
            console.log('statement 2');
            return Promise.reject(new Error('error')); 
        }
        return Promise.resolve();
    }
    

    Of course, this particular example doesn't make much sense, because none of your cases is asynchronous and there's no reason to use promises at all. Just use a synchronous function that throws exceptions. Typically, you'd have some return … in the end that is an actually asynchronous promise, not one that is fulfilled with undefined.

    Now, if you have such a function, and are tired of repeatedly writing return Promise.reject, you can use the Bluebird-specific Promise.try and Promise.method methods as syntactic sugar.

提交回复
热议问题