Following this question on stackoverflow, I've tried to make the promiseFor
method work without success. Since I don't have enough "reputation" to comment on that thread, here I am. This is the recursive loop:
var promiseFor = Promise.method(function(condition, action, value) {
if (!condition(value)) return value;
return action(value).then(promiseFor.bind(null, condition, action));
});
And this is how I've tested it:
promiseFor(function(arr){ //condition
return arr.length < 3;
}, function(arr){ //action
arr.push(arr.length+1);
return arr;
}, []) //initial value
.done(function(arr){
console.log(arr);
});
I was expecting to have an output of [1,2,3]
. But instead I got a TypeError: undefined is not a function
pointing to the line:
return action(value).then(promiseFor.bind(null, condition, action));
This happens to be the line that I haven't fully understood. What exactly does promiseFor.bind(null, condition, action)
do?
EDIT:
Thanks to kyrylkov I've changed the action
to:
function(arr){
return new Promise(function(resolve){
arr.push(arr.length + 1);
resolve(arr);
});
}
Working like a charm now.