-1

I have a somewhat complicated scenario and I'm not quite understanding why my call to Q.all is not returning an array of resolved promises. It is a mix of jQuery $.ajax calls and Q. calls. Here is the setup:

var saveThing1 = function(){
  return $.ajax({...});
}
var saveThing2 = function(){
  return $ajax({...});
}
var deleteThing2 = function(){
  return $.ajax({...});
}

saveThing1.then(function(){
  var promiseArr = [saveThing2(), saveThing2(), deleteThing2()];
  return Q.all(promiseArr);
}).then(function(response){
  var result1 = response[0];
  var result2 = response[1];
  var result3 = response[2];
});

From the Q docs:

promise.all()

Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected.

The value of response in this case ends up being the single Promise instead of the array of promise values. This is what the Chrome Dev Tools produces when I pause the debugger and log what the response value is:

Promise {}
  inspect:()
  promiseDispatch:(resolve, op, operands)
  valueOf:()

Another thing that I'm still scratching my head at is that the .then gets hit while the network requests are still pending, which means the promises in the array passed to Q.all should also be pending...

Joel Kinzel
  • 969
  • 2
  • 7
  • 19

1 Answers1

2

.all will not do anything with a function, it requires a Promise (or a Promise-like object). You are currently passing a function, not a promise. In order for this to work, all of your functions need to be called:

var saveThing1 = function(){
  return $.ajax({...});
}
var saveThing2 = function(){
  return $ajax({...});
}
var deleteThing2 = function(){
  return $.ajax({...});
}

saveThing1().then(function(){
  // populate the array with returned promises, not functions that return promises
  var promiseArr = [saveThing2(), saveThing2(), deleteThing2()];
  return Q.all(promiseArr);
}).then(function(response){
  var result1 = response[0];
  var result2 = response[1];
  var result3 = response[2];
});
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • Sorry, they are being called in my code. I generalized it on here (obviously) and cut some of the bloat/unrelated things out. I've updated the example code. – Joel Kinzel Aug 03 '16 at 22:37