grep数组的jqXHR对象 - 不能获得200的状态,只有503

时间:2014-05-14 21:55:21

标签: jquery ajax promise

我试图根据jqXHR状态过滤ajax Promise对象的数组。我只能在503的状态下获得状态,当它的状态为200时,状态未定义。如何过滤数组,仅返回状态为200

的jqXHR对象
var userData = {};  
userData.user1 = {"creds":    {"userid":"user1@test.com","password":"user1pass","country":"us"}};
userData.user2 = {"creds":    {"userid":"user2@test.com","password":"user2pass","country":"mx"}};
userData.user3 = {"creds":    {"userid":"user3@test.com","password":"user3pass","country":"ca"}};
function loginUser(credentials){
    var requests = $.map(credentials, function(k, v){
        return $.ajax({
            url : '/path/to/my/uri', 
            type : 'post',
            contentType : 'application/json',
            data : JSON.stringify(v)
        });
    });
    console.log(requests);
    // return a promise that will resolve when all ajax calls are done
    return $.when.apply($, requests);
}

loginUser(userData).always(function() {
    // all logins completed here
    successes = $.grep(requests, function(v, i){
        console.log(v.status); // only outputs 503
        return v.status == 200; // undefined
    });
});

1 个答案:

答案 0 :(得分:1)

这是因为承诺在$.ajax调用中解决了实际值而不是XHR本身。

如果您只想获得成功,可以使用xhr本身而不是结果来解决:

var requests = $.map(credentials, function(k, v){
    var xhr = $.ajax({
        url : '/path/to/my/uri', 
        type : 'post',
        contentType : 'application/json',
        data : JSON.stringify(v)
    });
    var xhr2 = xhr.then(function(result){ return xhr; }); //resolve with original
    return xhr2;
});

或者,您可以自己处理错误并仅访问成功的延迟对象,从here我自己的答案中窃取:

//returns only fulfilled values from a list of promises
function some(promises){
    var d = $.Deferred(), results = [];
    var remaining = promises.length;
    for(var i = 0; i < promises.length; i++){
        promises[i].then(function(res){
            results.push(res); // on success, add to results
        }).always(function(res){
            remaining--; // always mark as finished
            if(!remaining) d.resolve(results);
        })
    }
    return d.promise(); // return a promise on the remaining values
}

并做:

function loginUser(credentials){
   ...
   return some(requests);
}

loginUser(userData).then(function(results){
    //results is only the results of successful requests here.
});