在jquery $ .when(ajax).done(function(){do sth}中,我如何回调两次到同一个回调函数?

时间:2018-05-06 17:27:22

标签: javascript jquery asynchronous jquery-deferred

在jquery中,我有以下代码:

A部分:

$.when(result = $.startAsyncRequest(arg)).done(function(){
    console.log(result); // this should be called every time something is returned   
    if (result.hasOwnProperty("responseJSON")){
       console.log("build frontend table using completed task");
    }

});

B部分:

jQuery.extend({

   startAsyncRequest: function(arg){
       console.log(arg);
       $.when(result = makeAjaxRequest(arg)).done(function(){
           var taskid = result.taskid;
           var taskurl = "someurl" + taskid;
           startProgressBar(taskurl, {
           onSuccess: function(){
               $.when(result2 = makeAjaxRequest(taskid)).done(function(){
                  console.log("received completed task"); 
                  return result2;
               });
           });
           return "starting progress bar";
       });
       return "started task";
    }

});

A部分启动一个函数(B部分),其中包含几个ajax post请求,所有这些请求都是延迟的。其中一个请求是在进度条完成后基于回调进行的。

每次startAsyncRequest返回时,我都希望它返回到A部分并将结果记录到控制台。所以我希望它会多次返回,但它只返回一次(第一个请求,#34;启动任务")。

有办法做到这一点吗?

我不想将startAsyncRequest分解为多个函数,因为A部分在我的代码中重复了很多次,我希望它包含所有的任务调用,进度条和任务检索逻辑一个功能。

2 个答案:

答案 0 :(得分:0)

解决方案是 -

A部分:

$.startAsyncRequest(arg, function(result){
    console.log(result); // this should be called every time something is returned   
    if (result.hasOwnProperty("responseJSON")){
       console.log("build frontend table using completed task");
    }

});

B部分:

jQuery.extend({

   startAsyncRequest: function(arg, callbackFct){
       console.log(arg);
       $.when(result = makeAjaxRequest(arg)).done(function(){
           var taskid = result.taskid;
           var taskurl = "someurl" + taskid;
           startProgressBar(taskurl, {
           onSuccess: function(){
               $.when(result2 = makeAjaxRequest(taskid)).done(function(){
                  console.log("received completed task"); 
                  callbackFct(result2);
               });
           });
           return callbackFct("starting progress bar");
       });
       return callbackFct("started task");
    }

});

答案 1 :(得分:-2)

请检查:https://api.jquery.com/category/deferred-object/

function wrap(ajaxRequest){
  var defer = $.Deferred();
  ajaxRequest.done(function(resp){
     defer.notify({ "message" : "Done Success", resp : resp })
  }).fail(function(resp){
     defer.notify({ "message" : "Error Failure", resp : resp });
  });
  setTimeout(function(){
     defer.notify({ "message" : "Request is made", resp : null });
  })
  return defer.promise();
}

/// Calling function


  wrap($.ajax({
   // params
  })).progress(function(obj){
     console.log(obj)
  })