最佳答案
如何从发出异步请求的函数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`}使用Node.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`}使用Promise的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`}