javascript js函数内部函数并等待返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17879295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:57:51  来源:igfitidea点击:

js function inside function and wait for return value

javascriptjqueryfunction

提问by Lauris Kuznecovs

$(document).ready(function(){

    // Global function (will be include in any HTML file)
    function m3_result(size_1, size_2, size_3){
        $.get('http://www.google.com', function(data){
            return data;
        });
    }   

    // Another function
    function calculate(){
        var size_1 = parseFloat($('#add_document_form #size_1').val());
        var size_2 = parseFloat($('#add_document_form #size_2').val());
        var size_3 = parseFloat($('#add_document_form #size_3').val());          
        var ax = m3_result(size_1, size_2, size_3);

        alert(ax); // Here ax return: UNDEFINED  
    }

    // Run
    calculate();
});

Results are "undefined", but I would like that calculate() will wait for m3_result() to execute. I see that here problem is coming when I added $.get(), but its needed...

结果是“未定义的”,但我希望calculate() 将等待m3_result() 执行。当我添加 $.get() 时,我看到这里出现了问题,但它需要......

I have searching for callback() like functions, but none fit to my needs, or I just didnt put that right. Any help will be highly appreciated, thanks.

我正在寻找类似 callback() 的函数,但没有一个适合我的需要,或者我只是没有把它放在正确的位置。任何帮助将不胜感激,谢谢。



GET url will be localy and element IDs are also ok.

GET url 将是本地的,元素 ID 也可以。

回答by Alnitak

You can't return a result from an asynchronous function, instead you can return a promiseto supply that value later, which as it happens is the jqXHRobject returned by $.get:

您不能从异步函数返回结果,相反,您可以返回一个承诺以在以后提供该值,这恰好是由jqXHR返回的对象$.get

function m3_result() {
     return $.get(...)
}

and do the same in calculate:

并在计算中做同样的事情:

function calculate() {
    ...
    return m3_result(...); 
}

and then wait for the result, which will be passed as a parameter to the callback registered with the .donefunction:

然后等待结果,该结果将作为参数传递给.done函数注册的回调函数:

calculate().done(function(result) {
    alert(result);
});