foo
发出异步请求。如何从返回响应/结果
福
我尝试从回调中返回值,并将结果赋给函数内部的一个局部变量并返回该变量,但这些方法都没有真正返回响应(它们都返回
undefined
或者变量的初始值
result
是)。
使用jQuery的示例
ajax
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result; // It always returns `undefined`
}
示例使用js节点:
function foo() {
var result;
fs.readFile("path/to/file", function(err, data) {
result = data;
// return data; // <- I tried that one as well
});
return result; // It always returns `undefined`
}
示例使用
then
承诺块:
function foo() {
var result;
fetch(url).then(function(response) {
result = response;
// return response; // <- I tried that one as well
});
return result; // It always returns `undefined`
}