简体   繁体   中英

How to refactor a “callback pyramid” into promise-based version

I'm currently struggeling to really understand how to refactor my code to use promises/the Q library.

Consider the following common basic example: I have a testcase that imports the same file twice into a mongodb and then checks whether the dataset name for the second import got some modifier at the end.

importDataSet('myFile.csv',function () {
  importDataSet('myFile.csv',function () {
    DataSet.find({title: 1}, function (err, result) {
        result.length.should.be.equal(2);
        result[0].title.should.startWith('myFile');
        result[1].title.should.startWith('myFile');
        result[0].title.should.not.be.equal(result[0].title);
        done();
      });
    });
  });
  done();
}); 

(done() is the final callback):

So how would I do this using promises? Preferably without changing the function signatures, (I followed the convention to have callbacks as the last parameter).

I am not sure why done() is called twice in your code, but without that, it may look similar to:

importDataSet('myFile.csv')
  .then(function () {
  return importDataSet('myFile.csv')
}).then(function () {
  return DataSet.find({title: 1})
}).then(function (result) {
  result.length.should.be.equal(2);
  result[0].title.should.startWith('myFile');
  result[1].title.should.startWith('myFile');
  result[0].title.should.not.be.equal(result[0].title);
  done();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM