Work with 1 or more jQuery promises

I make one or more REST / ajax calls to validate some user data. The remaining calls work well and the information is returned. The problem I am facing is not the part of the code that looks something like this.

function ensureUsers(recipients){
  var promises = [];
  for(var key in recipients){
      var payload = {'property':recipients[key]};
      promises.push( $.ajax({...}));
  }
  return $.when.apply($,promises);    
}

....

ensureUsers(users) // users is an array of 1 or more users
  .done(function(){
     console.log(arguments);
  )}

If there is more than one user in the source array, the arguments in my code are .donestructured as follows:

[[Object,"success",Object],[Object,"success",Object]...]

Then I can iterate over each result, check the status and continue.

However, if there is only one user in the source array, it .donereceives the following arguments:

[Object,"success",Object]

It seems strange to me that the structure of the returnee will change so. I could not find anything about this particular problem, so I hacked a solution

var promises = Array.prototype.slice.call(arguments);
if(!Array.isArray(promises[0])){
    promises = [promises];  
}

, ? promises 1 ajax jQuery?

+4
2

, , , .

, jQuery . $.when, , , . , jQuery promises () .

, , :

  • $.when Promise.all :

    var promises = [];
    for (var p of recipients) {
        promises.push( $.ajax({…}));
    }
    
    Promise.all(promises)
    .then(function(results) {
         console.log(results);
    })
    
  • ( $.ajax(), 3), , $.when

    var promises = [];
    for (var p of recipients) {
        promises.push( $.ajax({…}).then(function(data, textStatus, jqXHR) {
            return data;
        }) );
    }
    
    $.when.apply($, promises)
    .then(function() {
         console.log(arguments);
    })
    
+3

, . , $.when, Promise, . , , , .

, , , , "" , .

..

function ensureUsers(recipients){
  var promises = [$.Deferred().resolve()];
  for(var key in recipients){
    var payload = {'property':recipients[key]};
    promises.push( $.ajax({...}));
  }
  return $.when.apply($,promises);    
}

, , , , .

+1

Source: https://habr.com/ru/post/1658273/


All Articles