0

我有一个调用异步函数的函数。我的示例使用 ajax,但它实际上是异步的。

我正在尝试在 ajax 调用的成功中添加其他信息。

发生的顺序:

-my 函数被调用,参数是 $.ajax 调用。

-我的函数需要在 $.ajax.success 调用中添加 1 行代码

我的代码如下所示:

function myFunct(settings, callback){
   if(!callback)return;
   var x = 100;
   //here is where i have issues, as i want 
   //to be able to adjust the success function
   // to also have 1 line of code, a decrementer.
   //I want to do something like settings.success = "x--;" + settings.success;

   callback(settings);

   //I also wasnt sure if you could wrap 'callback' 
   //with a success function when the inner success function executes
}

示例调用:

 var settings = "";//settings of the ajax call.
 myFunct(settings, function(x){ $.ajax(x);});
4

1 回答 1

3

如果您确保回调始终返回一个承诺对象,您可以使用.done()

function myFunct( settings, callback ) {
    if (!callback) return;
    var x = 100;

    callback(settings).done(function(){
        x--;
    });
}
var settings = { url: "foobar.php" };
myFunct( settings, function(x) {
    return $.ajax(x);
})

可以肯定的var x = 100是,这只是一个例子,对吗?就目前而言,它将超出范围并且毫无意义。

于 2012-09-26T18:17:50.430 回答