1

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.

Community
  • 1
  • 1
Gob
  • 305
  • 2
  • 11
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Dave Newton Aug 06 '15 at 18:51
  • 1
    Ah, I should have made that `Promise.resolve(action(value)).then(…)` - someone whose `action` doesn't return a promise would have to trip over that some day. You can fix that by doing `return Promise.resolve(arr);`. Or have a look at [this alternative pattern](http://stackoverflow.com/a/29396005/1048572). – Bergi Aug 06 '15 at 19:13

1 Answers1

0

In your test, action (2nd argument in anonymous function wrapped in Promise.method) is a function that returns an array, not a promise:

function(arr){
  arr.push(arr.length+1);
  return arr;
}

As a result you get the error in call action(value).then because the array doesn't have then method.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
krl
  • 5,087
  • 4
  • 36
  • 53
  • Thank you, totally didn't hink of that. Changed it to return a `new Promise` and now it's behaving the way I expected. – Gob Aug 06 '15 at 19:04