Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript $.when和回调_Javascript_Jquery - Fatal编程技术网

Javascript $.when和回调

Javascript $.when和回调,javascript,jquery,Javascript,Jquery,我正在寻找一种更整洁的方法: var f1 = function(){}; var f2 = function(){}; doSomething('ArbritraryString',f1); //does xhr, and then runs f1 on callback doSomething('ArbritraryString',f2); //does xhr, and then runs f2 on callback $.when($.get('

我正在寻找一种更整洁的方法:

    var f1 = function(){};
    var f2 = function(){};
    doSomething('ArbritraryString',f1); //does xhr, and then runs f1 on callback
    doSomething('ArbritraryString',f2); //does xhr, and then runs f2 on callback

    $.when($.get('myJson',f1,f2)).then(function(ret1, ret2, ret3){

        //doStuff
    });
有什么想法吗

doSomething
函数实际上只是调用空的f1/f2函数,因此我有一个
$的回调处理程序

理想情况下,我想要

$.when($.get('myJson',doSomething('ArbritraryString',function(){}); ,doSomething('ArbritraryString',function(){}))).then(function(ret1, ret2, ret3){

    //doStuff
});
让jquery神奇地知道doSomething中的第二个参数是它必须注意的回调

doSomething
如下所示:

doSomething:function(name,callbackFunction){
    /*snip logic 

    */
    $.get(name, function(data){
            /*some more logic 


            */

            if(typeof(callbackFunction)==='function'){
                callbackFunction();
            }
        });
    }
},

更改
doSomething
,使其不接受回调,只返回jqXHR对象(以
return$.get
结束),然后您可以使用
$。正确跟踪所有jqXHR对象的进度时:

$.when(
        doSomething('ArbritraryString'),
        doSomething('ArbritraryString'),
        $.get('myJson')
    ).done(function(ret1, ret2, ret3){
        // all three succeeded
    });

如果
doSomething
需要执行某种附加处理,然后才能将其视为已解决,则此函数应创建自己的延迟对象,并返回该对象的
.promise()
值,而不是直接返回
$.get
。有关此方法的更多信息,请参见。

中的示例。您希望“更整洁”的部分是什么?您实际上想做什么?这是一个xhr,加载脚本,然后在之后加载$。我想知道如何重写它,这样就不必在一个函数参数外声明两个空函数。你能修改
doSomething
?它返回什么?为什么需要
jQuery.when