Managing promise dependencies

后端 未结 3 643
暖寄归人
暖寄归人 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:46

    It is certainly not an antipattern to return promises within thens, flattening nested promises is a feature of the promise spec.

    Here's a possible rewrite, though I'm not sure it's cleaner:

    var doStuff = function () {
    
      promise1()
      .then(function (value1) {
    
        return promise2()
        .then(function (value2) {
    
          return promise3(value1)
          .then(successFunction)
          .finally(function() {
            cleanup(null, value1, value2);
          });
    
        })
        .finally(function() {
          cleanup(null, value1, null);
        });
    
      })
      .finally(function () {
        cleanup(null, null, null);
      });
    
    };
    

    Or another option, with atomic cleanup functions:

    var doStuff = function () {
    
      promise1()
      .then(function (value1) {
    
        return promise2()
        .then(function (value2) {
    
          return promise3(value1)
          .then(successFunction)
          .finally(function() {
            cleanup3(value2);
          });
    
        })
        .finally(function() {
          cleanup2(value1);
        });
    
      })
      .finally(function (err) {
        cleanup1(err);
      });
    
    };
    

    Really, I feel like there's not much you can do to clean this up. Event with vanilla try/catches, the best possible pattern is pretty similar to these.

提交回复
热议问题