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

后端 未结 3 622
刺人心
刺人心 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:29

    They aren't the same.

    Consider the situation where both statements are false. In that case, multiRejectExample() will never reject or resolve the returned promise, whereas tryExample() will "fall through" and resolve the promise automatically (with a value of undefined because you don't return anything).

    To demonstrate:

    var Promise = require('bluebird');
    
    function test1() {
      return Promise.try(function() { });
    }
    
    function test2() {
      return new Promise(function(resolve, reject) { });
    }
    
    test1().then(function() { console.log('resolved #1'); });
    test2().then(function() { console.log('resolved #2'); });
    

    This will log resolved #1 but not resolved #2 because the promise is never actually resolved (nor rejected).

提交回复
热议问题