如何创建一个可能在其中调用ajax的deffered函数?

时间:2016-02-01 14:03:08

标签: javascript jquery ajax promise

我试图用$ .when(func())连接几个AJAX调用。然后(func2())。then(func3());

但是,我的第一个func()不是直接的AJAX调用,但 CAN 内部有一个AJAX调用,具体取决于其中的另一个AJAX调用。现在,我的func2(),没有等待func()完成,这导致了我的问题。我觉得我很接近解决方案,但不能完全实现。我在这里错过了什么?为什么func2()不等待dfd.resolve()?这是我突出问题的简化版本。

//First in the chain...
var request = function() {
    //New Deffered....
    var dfd = new $.Deferred(),
        isPaid,
        uniqueId,
        loadUrl = '/some/url/json',
        saveUrl = '/some/other/url/';

    //First ajax call to check if our object is PAID or NOT
    $.get(loadUrl, function(data){
      isPaid = (data.isPaid === "true"),
      uniqueId =  data.latestPayNumber;
    }).done(function(){
      //If it's not paid, we'll have to create a NEW object in our database
      if(!isPaid) {
        params = [];
        params.push({ name: 'someID', value: 'value_one' });
        params.push({ name: 'someIDTwo', value: 'value_two' });
        serialisedParams = $.param(params); 
        //NOW HERE: Is another ajax call that MAY or MAY NOT happen depending on isPaid...but we have to account for it         
        $.post( saveUrl, serialisedParams)
        .done(function(data){
          //Now after this call, we have the uniqueId that we need...resolve and continue
          uniqueId = data.newUniqueId;
          dfd.resolve();
        });
      } 
      //If it was paid, we don't need to run any other ajax calls, we have our uniqueId
      else {
        parentDataBundleId = payeDataBundleId;
        dfd.resolve();        
      }                          
    });  
    return dfd.promise();                 
},
//Second in chain
chained = $.when(request()).then(function( data ) {
          //Build some params here.... and post
          return $.post( saveUrl, serialisedParams );
}),
//Third in chain
chainedTwo = chained.then(function(data){
            //Build more params......              
            return $.post( saveUrl, serialisedParams );
});

//After all calls have exectued in order, we're done...
chainedTwo.done(function( data ) {
  console.log("Weeeeee we're done!");
});  

0 个答案:

没有答案