Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.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 异步回调后返回_Javascript_Asynchronous_Callback_Return - Fatal编程技术网

Javascript 异步回调后返回

Javascript 异步回调后返回,javascript,asynchronous,callback,return,Javascript,Asynchronous,Callback,Return,考虑给定的代码 function foo() { var bar = []; asyncRequest.get(function(data) { bar = data; }); return bar; } 当它充满了回调中的数据而不是之前的数据时,如何返回该条?在50%的情况下,返回时间提前,然后回调完成,返回空数组 当它充满了回调中的数据而不是之前的数据时,如何返回该条 你不能。相反,让函数接受它调用的回调,结果是: function foo

考虑给定的代码

function foo() {
    var bar = [];
    asyncRequest.get(function(data) {
        bar = data;
    });

    return bar;
}
当它充满了回调中的数据而不是之前的数据时,如何返回该条?在50%的情况下,返回时间提前,然后回调完成,返回空数组

当它充满了回调中的数据而不是之前的数据时,如何返回该条

你不能。相反,让函数接受它调用的回调,结果是:

function foo(callback) {
    asyncRequest.get(function(data) {
        // (More stuff here, presumably)
        callback(data);
    });
}
或者,如果它真的只是一个通行证(在我写的地方没有什么)(这里大概有更多的东西),那么:


你不能。这就是函数首先接受回调的原因。在执行异步任务时,不能在该位置使用return。无论您想对异步请求获取的值做什么,都可以从回调函数中执行
function foo(callback) {
    asyncRequest.get(callback);
}