This article gives a brief introduction to the concept and usage of callback functions in the JavaScript programming language.

本文简要介绍了JavaScript编程语言中的回调函数的概念和用法。

函数就是对象 (Functions are Objects)

The first thing we need to know is that in Javascript, functions are first-class objects. As such, we can work with them in the same way we work with other objects, like assigning them to variables and passing them as arguments into other functions. This is important, because it’s the latter technique that allows us to extend functionality in our applications.

我们需要知道的第一件事是,在Javascript中,函数是一流的对象。 这样,我们可以像处理其他对象一样使用它们,例如将它们分配给变量并将它们作为参数传递给其他函数。 这很重要,因为后一种技术使我们能够扩展应用程序中的功能。

回调函数 (Callback Functions)

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed. It’s the combination of these two that allow us to extend our functionality.

回调函数是一个作为参数传递给另一个函数的函数,以后将被“回调”。 接受其他函数作为参数的函数被称为高阶函数 ,其包含所述回调函数被执行为逻辑。 两者的结合使我们能够扩展功能。

To illustrate callbacks, let’s start with a simple example:

为了说明回调,让我们从一个简单的示例开始:

function createQuote(quote, callback){ var myQuote = "Like I always say, " + quote;callback(myQuote); // 2
}function logQuote(quote){console.log(quote);
}createQuote("eat your vegetables!", logQuote); // 1// Result in console:
// Like I always say, eat your vegetables!

In the above example, createQuote is the higher-order function, which accepts two arguments, the second one being the callback. The logQuote function is being used to pass in as our callback function. When we execute the createQuote function (1), notice that we are not appending parentheses to logQuote when we pass it in as an argument. This is because we do not want to execute our callback function right away, we simply want to pass the function definition along to the higher-order function so that it can be executed later.

在上面的示例中, createQuote是高阶函数,它接受两个参数,第二个参数是回调。 logQuote函数被用作我们的回调函数。 当我们执行createQuote函数(1)时 ,请注意,当我们将logQuote作为参数传递时,没有在logQuote 后面加上括号。 这是因为我们不想立即执行回调函数,我们只想将函数定义传递给高阶函数,以便以后可以执行。

Also, we need to ensure that if the callback function we pass in expects arguments, that we supply those arguments when executing the callback (2). In the above example, that would be the callback(myQuote); statement, since we know that logQuote expects a quote to be passed in.

另外,我们需要确保如果传入的回调函数期望参数,那么在执行回调(2)时我们将提供这些参数。 在上面的示例中,这将是callback(myQuote); 语句,因为我们知道logQuote希望传递一个报价。

Additionally, we can pass in anonymous functions as callbacks. The below call to createQuote would have the same result as the above example:

此外,我们可以将匿名函数作为回调传递。 以下对createQuote调用将具有与以上示例相同的结果:

createQuote("eat your vegetables!", function(quote){ console.log(quote);
});

Incidentally, you don’t have to use the word “callback” as the name of your argument, Javascript just needs to know that it’s the correct argument name. Based on the above example, the below function will behave in exactly the same manner.

顺便说一句,你不必用“回拨”作为参数的名称,使用Javascript只需要知道它是正确的参数名称。 根据上面的示例,下面的函数将以完全相同的方式运行。

function createQuote(quote, functionToCall) { var myQuote = "Like I always say, " + quote;functionToCall(myQuote);
}

为什么要使用回调功能? (Why use Callback functions?)

Most of the time we are creating programs and applications that operate in a synchronous manner. In other words, some of our operations are started only after the preceding ones have completed. Often when we request data from other sources, such as an external API, we don’t always know when our data will be served back. In these instances we want to wait for the response, but we don’t always want our entire application grinding to a halt while our data is being fetched. These situations are where callback functions come in handy.

大多数时候,我们正在创建以同步方式运行的程序和应用程序。 换句话说,我们的某些操作仅在上述操作完成后才开始。 通常,当我们从其他来源(例如外部API)请求数据时,我们并不总是知道何时将数据送回。 在这些情况下,我们希望等待响应,但是我们并不总是希望在获取数据时整个应用程序停止运行。 在这些情况下,回调函数非常有用。

Let’s take a look at an example that simulates a request to a server:

让我们看一个模拟对服务器请求的示例:

function serverRequest(query, callback){setTimeout(function(){var response = query + "full!";callback(response);},5000);
}function getResults(results){console.log("Response from the server: " + results);
}serverRequest("The glass is half ", getResults);// Result in console after 5 second delay:
// Response from the server: The glass is half full!

In the above example, we make a mock request to a server. After 5 seconds elapse the response is modified and then our callback function getResults gets executed. To see this in action, you can copy/paste the above code into your browser’s developer tool and execute it.

在上面的示例中,我们向服务器发出了模拟请求。 5秒钟后,将修改响应,然后执行我们的回调函数getResults 。 要查看实际效果,您可以将以上代码复制/粘贴到浏览器的开发人员工具中并执行。

Also, if you are already familiar with setTimeout, then you’ve been using callback functions all along. The anonymous function argument passed into the above example’s setTimeout function call is also a callback! So the example’s original callback is actually executed by another callback. Be careful not to nest too many callbacks if you can help it, as this can lead to something called “callback hell”! As the name implies, it isn’t a joy to deal with.

另外,如果您已经熟悉setTimeout ,那么您一直都在使用回调函数。 传递到上述示例的setTimeout函数调用中的匿名函数参数也是回调! 因此,该示例的原始回调实际上是由另一个回调执行的。 如果可以帮助,请注意不要嵌套太多回调,因为这可能会导致“回调地狱”! 顾名思义,处理它并不是一件愉快的事情。

翻译自: https://www.freecodecamp.org/news/what-is-a-callback-function-in-javascript/

什么是JavaScript中的回调函数?相关推荐

  1. 理解javascript中的回调函数(callback)【转】

    在JavaScrip中,function是内置的类对象,也就是说它是一种类型的对象,可以和其它String.Array.Number.Object类的对象一样用于内置对象的管理.因为function实 ...

  2. 关于javascript中的回调函数

    关于javascript中的回调函数 原文地址:http://blog.csdn.net/sicluoyi/article/details/1737969 考虑一个这样的例子: 假如某个项目的底层和高 ...

  3. 理解javascript中的回调函数(callback)

    理解javascript中的回调函数(callback) 在JavaScrip中,function是内置的类对象,也就是说它是一种类型的对象,可以和其它String.Array.Number.Obje ...

  4. 理解与使用Javascript中的回调函数

    在Javascript中,函数是第一类对象,这意味着函数可以像对象一样按照第一类管理被使用.既然函数实际上是对象:它们能被"存储"在变量中,能作为函数参数被传递,能在函数中被创建, ...

  5. 【JavaScript】理解与使用Javascript中的回调函数

    在Javascript中,函数是第一类对象,这意味着函数可以像对象一样按照第一类管理被使用.既然函数实际上是对象:它们能被"存储"在变量中,能作为函数参数被传递,能在函数中被创建, ...

  6. JavaScript中的回调函数(callback)

    前言 callback,大家都知道是回调函数的意思.如果让你举些callback的例子,我相信你可以举出一堆.但callback的概念你知道吗?你自己在实际应用中能不能合理利用回调实现功能? 我们在平 ...

  7. bootstraptable 加载完成回调函数_牛皮了!头一次见有大佬把「JavaScript中的回调函数」详解得如此清晰明了...

    前言 callback,大家都知道是回调函数的意思.但是你对这个概念应该是模模糊糊.比如Ajax,你只知道去调用返回函数,如果对callback没有理解清楚,估计你在学习Node.js后会崩溃,因为c ...

  8. 浅聊JavaScript中的回调函数

    Time will tell. 一.JavaScript中的函数 在 JavaScript 中,函数也是一种 data,一种数据,只不过这种数据比较特殊,它里面存的是代码,而且这种data可以被调用执 ...

  9. javaScript中的回调函数

    ​ <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8&qu ...

最新文章

  1. Qt安装后配置环境变量(Mac)
  2. OSPF 疑重难要14点--转屎壳Q岛的一个文章
  3. php面试框架的执行流程图,ThinkPHP2.2框架执行流程图,ThinkPHP控制器的执行流程
  4. 【错误记录】VMware 虚拟机报错 ( 向 VMWare 虚拟机中的 Ubuntu 系统拷贝文件时磁盘空间不足 )
  5. 【Unity3D基础教程】给初学者看的Unity教程(四):通过制作Flappy Bird了解Native 2D中的RigidBody2D和Collider2D...
  6. 编译linux系统到开发板,迅为3399开发板Linux固件编译-Ubuntu16系统编译
  7. vector的reserve和resize
  8. Why Opportunity list is empty
  9. C++之virtual 方法
  10. [SCSS] Pure CSS for multiline truncation with ellipsis
  11. 创建dataframe_Spark原理与实战(五) Spark核心数据抽象DataFrame
  12. Java中做比较介绍
  13. linux network 脚本,自动修改Linux下/etc/sysconfig/network-scripts/ifcfg-ethX网卡文件的脚本...
  14. 修复easyMule for Mac 2.0崩溃造成的任务丢失
  15. linux lightdm自动登录,设置了XFCE/lightDM启用自动登录,还是需要'点击'登录两字才能进入桌面...
  16. 数字化门店| 奶茶店智慧管理系统
  17. 动漫里的op、ed、OVA、ost、bl、gl代表什么意思
  18. DBCA创建数据库实例
  19. UnrealEngine4蓝图功能_关卡切换后的玩家出身点定位功能实现
  20. 【5.20】用 canvas 绘制一朵玫瑰

热门文章

  1. 信号 09 | 函数pause
  2. mysql数据库实用教程答案
  3. 现在做Android开发有前途吗?附面试题答案
  4. 2017-2018-1 20179215《Linux内核原理与分析》第二周作业
  5. ImageView缩放选项
  6. SqlServer双机热备技术实践笔记
  7. 如何看待和选择基础设施软件
  8. iOS Application Security
  9. Docker安装部署ELK教程 (Elasticsearch+Kibana+Logstash)
  10. 在使用win 7 无线承载网络时,启动该服务时,有时会提示:组或资源的状态不是执行请求操作的正确状态。 网上有文章指出,解决这个问题的方法是在设备管理器中启动“Microsoft托管网络虚拟适配