简体   繁体   English

如何将“回调金字塔”重构为基于承诺的版本

[英]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. 我目前正在努力了解如何重构我的代码以使用promises / Q库。

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. 考虑以下常见的基本示例:我有一个测试用例,它将同一个文件两次导入mongodb,然后检查第二个导入的数据集名称是否在最后得到了一些修饰符。

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): (done()是最后的回调):

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: 我不确定为什么在你的代码中调用done()两次,但没有它,它可能看起来类似于:

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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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