1

I'm really trying hard to understand the behavior or JQuery's promise().

I want to do 3 (unrelated, but back-to-back) AJAX queries :

1. GET the user data
2. POST an image
3. POST another image

Then, I'm doing a load of things that are based on then results of said queries.

Now, the $.when(ajax, ajax, ajax).then(userData, img1, img2) functions work great for this as of now, but what if I want my ajax calls to be wrapped around conditions, as so :

$.when(
 if(...){
   $.ajax({ ...GET user data... });
 }
 if(...){
   $.ajax({ ...POST image... });
 }
 if(...){
   $.ajax({ ...POST image... });
 }
).then(function(userData, img1, img2){
 if(img1){
  ...do something with img1...
 }
 ...same for other responses...
});

I'm aware that my code doesn't contain any promise, but really, everything I've tried failed pretty badly in this scenario.

Any hint/tip appreciated. Thanks.

Justin01
  • 288
  • 1
  • 4
  • 14
  • How about wrapping the ajax functions in other functions where you can use your conditions e.g: `$.when(function ajaxForSomeCondition(){if (someCondition){return $.ajax...}})` – Bwaxxlo Apr 28 '15 at 10:14
  • also see [if with asynchronous case](http://stackoverflow.com/a/29802688/1048572), [rewrite a series of conditional statements](http://stackoverflow.com/a/21913675/1048572) or [promises and if/else statement](http://stackoverflow.com/q/21911369/1048572) – Bergi Apr 28 '15 at 13:06

2 Answers2

3

You can pass non-promises to jQuery's $.when it'll deal them just fine:

$.when(15, undefined, $.ajax(...)).then(function(fifteen, undef, result){
    // this will run when the result is ready
});

If you want to do something based on the result of the calls you can chain them via .then, if you want to run them one after the other, you can use thenable chaining instead of $.when which works concurrently.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
1

I think you're looking for the ternary operator, and a way to build default value promises:

$.when(
  … ? $.ajax({/* GET user data */}) : $.when(null),
  … ? $.ajax({/* POST first image */}) : $.when(null),
  … ? $.ajax({/* POST second image */}) : $.when(null)
).then(function(userData, img1, img2){
  if (userData)
    … // do something with userData
  if (img1)
    … // do something with img1
  …
});

This will, based on the respective condition, either send an ajax request and get a promise for its result, or construct an already-fulfilled promise for the value null. Then all of the three promises are awaited.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • (related: http://stackoverflow.com/questions/26599798/if-else-flow-in-promise-bluebird) – Bergi Jun 02 '15 at 17:25