axios 异步回调 处理
为了轻松起见,AJAX的Catch 22在大多数情况下是我们想要编写“同步代码”的原因,但是异步是避免某些非常讨厌的可用性问题的唯一方法。 这意味着不能像我们想要的那样编写简单的代码,例如;
function doClick() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://example.com/products",false);
# Execution blocks here, waiting for the response to complete...
xmlhttp.send(null);
alert(xmlhttp.responseText);
}
…我们需要通过回调来处理,最简单的例子是…
var xmlhttp = new XMLHttpRequest();
function doClick() {
xmlhttp.open("GET","http://example.com/products",true);
// Set the callback
xmlhttp.onreadystatechange = handleResponse;
xmlhttp.send(null);
}
function handleResponse() {
if ( xmlhttp.readyState == 4 ) {
alert (xmlhttp.responseText);
}
}
…但是现在已经引入了更多潜在的问题。 现在,该回调依赖于可用的全局xmlhttp对象(任何重要大小的项目的全局变量通常都是有害的)。 如果用户不断触发doClick()
函数怎么办? 异步请求暂停一下咖啡然后在不久之后返回意外(需要超时)怎么办? 那只是初学者。
无论如何–几个有趣的项目正在努力使我们两全其美–异步请求但是(看起来像)阻塞了代码。 两者都是在扩展Javascript本身的基础上工作的,因此以前在手动编码方面付出的巨大努力被巧妙地隐藏在新的Javascript运算符或关键字后面。
叙述性Javascript
第一个是Narrative Javascript ,它添加了一个新的“阻塞运算符” ->
使您的代码变为类似;
function doClick() {
# Note the blocking operator...
var response = doHttpRequest->("http://example.com/products");
alert(response);
}
Narrative JS 概述是一个很好的起点。 Narrative JS的优点可能是它是纯Javascript-尽管文档建议使用Rhino之类的东西进行离线预处理,但您可能(理论上)可以在浏览器中按需预处理代码(以潜在的巨大性能成本),Javascript解析器是水仙 (也纯JS)。 至少,成为所有JS可能会使人们对使用它更有信心。
杰瓦奇
第二个是jwacs –具有高级继续支持的Javascript。 实际上,这不仅可以模拟阻塞代码,还可以添加四个新关键字 (和import语句),这还远远不够。 前面的示例(带有捆绑的jwacs实用程序API的帮助)变成了;
function doClick() {
var response = JwacsLib.fetchData("GET", "http://example.com/products"))
alert(response);
}
要查看扩展的Javascript,您需要查看上面的fetchData
定义;
fetchData: function(method, url)
{
var http = JwacsLib.getHttpObj();
var k = function_continuation;
http.onreadystatechange = function()
{
try
{
// Report results to the continuation on completion
if(http.readyState == 4)
{
// Check for errors
if(!(http.status == undefined ||
http.status == 0 ||
(http.status >= 200 && http.status < 300)))
{
var err = new Error("Server returned " + http.status);
throw err;
}
// No errors, so resume the continuation with the raw results
http.onreadystatechange = JwacsLib.emptyFunction;
resume k <- http.responseText;
}
}
catch(e)
{
// Errors are thrown as exceptions into the continuation
http.onreadystatechange = null;
throw e -> k;
}
};
http.open(method, url);
http.send(null);
suspend;
}
注意function_continuation
, suspend
, resume
和扩展throw: throw e -> k;
以上。 jwacs预处理器是用LISP编写的……
那么这里的总体感觉如何? 您会考虑使用这些吗?
对许多人来说,用新语法扩展Javascript的想法可能令人反感。 您还介绍了一些重要的依赖关系–以后的计划变更可能会导致重大的重写(当然,它们仍然都是非常原型)。
同时,用Java语言编写涉及异步处理和回调的非平凡内容会很快成为噩梦–为什么不使用一些智能语法来消除人工工作呢? 在这里,一般的方法对我来说似乎很好。
网络周
当我在这里时– 今晚在Webtuesday上刊登的一则快速广告, 帕特里斯(Patrice)谈论了他在Tilllate 总部进行Selenium (不仅是“ 更多Java ”,还知道是Java )的网络测试的经验。
翻译自: https://www.sitepoint.com/eliminating-async-javascript-callbacks-by-preprocessing/
axios 异步回调 处理