javascript - 对回调感到困惑

标签 javascript

我开始学习 JS 并遇到了回调和 promise 。我有点困惑,阅读了数十个来源,但找不到确切的答案。例如来自 mozilla 的代码

var xmlhttp = new XMLHttpRequest(),
method = 'GET',
url = 'https://developer.mozilla.org/';

xmlhttp.open(method, url, true);
xmlhttp.onload = function (data) {
   console.log(data)
};
xmlhttp.send();

来自 onload 的描述:

callback is the function to be executed when the request completes successfully. It receives a ProgressEvent object as its first argument. The value of this (i.e. the context) is the same XMLHttpRequest this callback is related to.

它实际上从哪里获得 ProgressEvent?我应该如何区分它和

var myFunc = function (data) {
    console.log(data);
}
myFunc('ALERT!!!');

我不应该将参数传递给函数吗?

最佳答案

回调函数作为参数传递给另一个稍后执行的函数。在您的情况下,您希望在 XMLHttpRequest 完成其工作后执行某些操作。因此,您需要传递一个成功函数,以便在 ajax 完成加载其内容后执行。

我们为什么要使用回调?

完成加载后,您可能想对 http 请求的结果做一些事情。您不能在 onload 处理程序中执行此操作。

xmlhttp.onload = function(result){
    // do stuff with result
}

但是你需要在 onload 事件处理程序中编写大量代码。因此通过传递回调可以保持工作区干净。在回调中编写用于处理结果的代码。参见以下代码

 function ajax(callback){

  var xmlhttp = new XMLHttpRequest(),
  method = 'GET',
  url = 'https://developer.mozilla.org/';

  xmlhttp.open(method, url, true);
  xmlhttp.onload = function (data) {
     callback(data) // your callback will execute after http request finish loading
  };
  xmlhttp.send();

}

function success(result){ // this function will be used as callback 
   // do stuff with result.
}

// call ajax function and pass the callback function to be executed after loading

ajax(success)

ProgressEvent :

ProgressEvent 对象包含与当前请求状态关联的数据。下面是您的进度事件对象。请参见红色下划线属性。loaded 是加载的字节数。total 是要加载的总字节数。这实际上是数据大小。因此您可以确定要加载多少字节和实际加载多少字节。如果这两个属性是类似然后加载完成。这就是 onload 所做的。加载完成后两者都是 191(字节)。我有一个大小为 191 字节的文件。这意味着加载完成。

enter image description here

关于javascript - 对回调感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48369817/

相关文章:

javascript - 使用 JavaScript 选择特定的 DOM 元素

javascript - 在函数中测试 onclick

javascript - 降低高度 Material 文本字段

javascript - 使用 Google Chrome 扩展程序登录后如何更改 UI?

javascript - 选择导航菜单链接时,如何更改背景图像和文本

php - 如果输入为空并且输入不是现有的 Twitter 帐户,如何停止我的 javascript 运行?

javascript - 当 TD 不包含任何 ID 时如何使用 JavaScript 获取 TD 值

javascript - 内容可编辑指令无法正常工作

javascript - meteor 动态下拉菜单不起作用

javascript - 使用 for 循环方法打印/记录数组中的对象