一、概述
我有一个foo
发出异步请求的函数。如何从 返回响应/结果foo
?
我正在尝试从回调中返回值,并将结果分配给函数内的局部变量并返回该变量,但这些方法都没有真正返回响应(它们都返回undefined
或变量的初始值)result
是)。
使用 jQueryajax
函数的示例:
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`
}
使用then
Promise 块的示例:
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`
}
二、详解
拥抱 JavaScript 的异步特性!虽然某些异步操作提供同步对应物(“Ajax”也是如此),但通常不鼓励使用它们,尤其是在浏览器上下文中。
JavaScript 在浏览器的 UI 线程中运行,任何长时间运行的进程都会锁定 UI,使其无响应。此外,JavaScript 的执行时间有上限,浏览器会询问用户是否继续执行。
所有这些都会导致非常糟糕的用户体验。用户将无法判断是否一切正常。此外,对于连接速度较慢的用户,效果会更差。
在下文中,我们将研究三种不同的解决方案,它们都建立在彼此之上:
- Promises with
async/await
(ES2017+,如果您使用转译器或再生器,则在旧浏览器中可用) - Callbacks (node中)
- Promises with
then()
(ES2015+,如果您使用众多 Promise 库之一,则可在较旧的浏览器中使用)
所有这三个都在当前浏览器和node7+ 中可用。
如若转载,请注明出处:https://www.javaidea.cn/article/8532.html