Justin01
Justin01

Reputation: 288

Confused about JQuery promises

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.

Upvotes: 1

Views: 77

Answers (2)

Bergi
Bergi

Reputation: 664297

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.

Upvotes: 1

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

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.

Upvotes: 3

Related Questions