El Kopyto El Kopyto - 10 months ago 59
Javascript Question

Chaining promises without using 'then' with Q library

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

var foo = new Foo();

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.

Answer Source

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...