I'm trying to call a chain of promises sequentially. I would like to pass some state across all the promises. I thought I'd be able to bind() my state but have been unable to get it working. My sample code looks like:
var Promise = require('bluebird');
...
function op1(state) {
return new Promise(function(resolve, reject) {
this.num += 1;
resolve();
});
}
function op2(state) {
return new Promise(function(resolve, reject) {
this.num += 1;
resolve();
});
}
function op3(state) {
return new Promise(function(resolve, reject) {
this.num += 1;
resolve();
});
}
function sequence(tasks, state) {
var current = Promise.cast();
for (var k = 0; k < tasks.length; ++k) {
current = current.thenReturn().then(tasks[k]);
}
return current.thenReturn();
}
var state = { yadda: "yadda",
num: 0 };
var q = [ op1, op2, op3 ];
var p = sequence( q, state );
var ret = p()
.then( function(val) {
console.log(val);
})
.catch ( function(val) {
console.error(val);
});
I've tried to simplify the problem to what I see in many example:
op1().bind(state).then(op2).then(op3);
However, this isn't working either.
I've also tried to change sequence() to the following (among various other things):
var current = Promise.cast().bind(state);
I am still very new to promises. I suspect I am missing something easy. Any advice or help would be much appreciated.
bindPromises; you probably need to bind the functions within them.bind(), etc.