Managing promise dependencies

后端 未结 3 614
暖寄归人
暖寄归人 2021-01-04 13:39

I\'m using Node.js and Bluebird to create some fairly complicated logic involving uncompressing a structured file, parsing JSON, creating and making changes to several Mongo

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 13:48

    This question might be more appropriate for code review but here is how I'd approach it given this example:

    var doStuff = function () {
      // Set up your promises based on their dependencies. In your example
      // promise2 does not use dependency1 so I left them unrelated.
      var dep1Promise = promise1();
      var dep2Promise = promise2();
      var dep3Promise = dependency1Promise.then(function(value){
        return promise3(value);
      });
    
      // Wait for all the promises the either succeed or error.
      allResolved([dep1Promise, dep2Promise, dep3Promise])
          .spread(function(dep1, dep2, dep3){
    
        var err = dep1.error || dep2.error || dep3.error;
        if (err){
          // If any errored, call the function you prescribed
          cleanupDependingOnSystemState(err, dep1.value, dep2.value);
        } else {
          // Call the success handler.
          successFunction(dep3.value);
        }
    };
    
    // Promise.all by default just fails on the first error, but since
    // you want to pass any partial results to cleanupDependingOnSystemState,
    // I added this helper.
    function allResolved(promises){
      return Promise.all(promises.map(function(promise){
        return promise.then(function(value){
          return {value: value};
        }, function(err){
          return {error: err};
        });
      });
    }
    

    The use of allResolved is only because of your callback specifics, if you had a more general error handler, you could simply resolve using Promise.all directly, or even:

    var doStuff = function () {
      // Set up your promises based on their dependencies. In your example
      // promise2 does not use dependency1 so I left them unrelated.
      var dep1Promise = promise1();
      var dep2Promise = promise2();
      var dep3Promise = dependency1Promise.then(function(value){
        return promise3(value);
      });
    
      dep3Promise.then(successFunction, cleanupDependingOnSystemState);
    };
    

提交回复
热议问题