Chaining promises without using 'then' with Q library

梦想与她 提交于 2019-12-25 07:59:14

问题


I'm trying to chain Q promises without 'then', so eventually the chain would look like this:

var foo = new Foo();
foo
.method1()
.method2()
.method3();

How to implement foo's methods so each one is executed once the promise of the previous one is resolved?

This question was marked as exact duplicate of this one but I'm trying to implement this using Q lib, not jQuery.


回答1:


I'm not sure if you are going to gain anything with this.

I suppose that you can do something like this:

function Foo() {
  var self = this,
      lastPromise = Promise.resolve();

  var chainPromise = function(method) {
    return function() {
      var args = Array.prototype.slice.call(arguments))
      lastPromise = lastPromise.then(function(){
        return method.apply(self, args);
      });
      return self;
    }
  }

  this.method1 = chainPromise(function() {
    // do the method1 stuff
    // return promise
  });

  this.method2 = chainPromise(function() {
    // do the method2 stuff
    // return promise
  });

  // etc...
}


来源:https://stackoverflow.com/questions/40747256/chaining-promises-without-using-then-with-q-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!