简体   繁体   English

在$ .when()。done中使用ajax promise

[英]Using ajax promise with $.when().done

I need two return values from two different ajax calling. 我需要两个不同的ajax调用的两个返回值。

I have two javascript functions : 我有两个JavaScript函数:

this.getVal1= function(numberDep){
    var promise = $.ajax({
        url:url, //REST url
        type:"GET",
        dataType:"json",
        contentType: "application/json"
    });
    return promise;
};

this.getVal2= function(){
    var promise = $.ajax({
        url:url, //another REST url
        type:"GET",
        dataType:"json",
        contentType: "application/json"
    });
    return promise;
};

How I call these two functions : 我如何称呼这两个功能:

 $.when(getVal1(17),getVal2())
 .done(function(_topdep,_alldep){
       console.log(_topdep);
       console.log(_alldep);

 });

Here are the result of each console.log : http://i.stack.imgur.com/IHBQx.png . 这是每个console.log的结果: http : //i.stack.imgur.com/IHBQx.png

What I supposed to return from first console.log is those 17 records, and the second console.log is 36 records (please have a look in the above image) . 我应该从第一个console.log返回的是这17条记录,而第二个console.log是36个记录(请在上图中查看)。

Any help would be much appreciated, thank you.. 任何帮助将不胜感激,谢谢..

Since those are ajax promises and the ajax promises have more than 1 callback param(data, status, jqXHR) the then callback will receive an array as the value for each callback. 由于这些是ajax承诺,并且ajax承诺具有多个回调参数(数据,状态,jqXHR),因此then回调将收到一个数组作为每个回调的值。 So to get the data you need to get the first member of each argument 因此,要获取数据,您需要获取每个参数的第一个成员

$.when(getVal1(17), getVal2())
.done(function (_topdep, _alldep) {
    console.log( _topdep[0] );
    console.log( _alldep[0] );

});

Demo: Fiddle 演示: 小提琴

I'm guessing you want to return the results of the two separate ajax calls after both finish? 我猜您想在两个完成后返回两个单独的ajax调用的结果吗? If that's the case, then you could wrap each ajax request in a Promise and use the Promise.all([promise1, promise2]) construct. 如果是这种情况,则可以将每个ajax请求包装在Promise然后使用Promise.all([promise1, promise2])构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM