Javascript Question

Jquery .then chain behavior

I have the following function that returns a function with an assinged

.then
function.

Func = function () {
return Func1([a, b])()
.then(_.bind(function () {
//something
}, this));
};


And later I assign another
.then
function to
Func
, like this:

Func2 = function(){
//something
this.Func()
.then(_.bind(function () {
//something
}, this));
};


Will there be a chain like
Func1().then().then()
or something else?

Answer

This is a promise. And on a promise you can do so much then as you like! ;)

function callback() {
    console.log("then");
}

var p = new Promise(function(resolve) {
    resolve();
}).then(callback);

p.then(callback);
p.then(callback).then(callback);
p.then(callback).then(callback).then(callback);

Working example.

Or as for your example:

var Func1 = function(param1) {
    return new Promise(function(resolve) {
        resolve();
    });
}

var Func = function() {
    return Func1(["a", "b"]).then(function() {
        console.log("then");
    }.bind(this));
};

var Func2 = function() {
    Func().then(function () {
        console.log("then");
    }.bind(this))
    .then(function() {
        console.log("then chain");
    });
};

Func2();

Working example.

Comments