加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

深入理解 JavaScript 回调函数

发布时间:2019-11-08 17:24:35 所属栏目:建站 来源:疯狂的技术宅
导读:JavaScript回调函数是成为一名成功的 JavaScript 开发人员必须要了解的一个重要概念。但是我相信,在阅读本文之后,你将能够克服以前使用回调方法遇到的所有障碍。 在开始之前,首先要确保我们对函数的理解是扎实的。 快速回顾:JavaScript 函数 什么是函

为了在回调的帮助下实现这个功能,代码应该如下所示:

  1. http.get('https://api.github.com/users', function(users) { 
  2.   /* Display all users */ 
  3.   console.log(users); 
  4.   http.get('https://api.github.com/repos/javascript/contributors?q=contributions&order=desc', function(contributors) { 
  5.   /* Display all top contributors */ 
  6.     console.log(contributors); 
  7.     http.get('https://api.github.com/users/Jhon', function(userData) { 
  8.     /* Display user with username 'Jhon' */ 
  9.       console.log(userData); 
  10.     }); 
  11.   }); 
  12. }); 

从上面的代码片段中,你可以看到代码变得更加难以理解,以及难以维护和修改。这是由回调函数的嵌套而引发的。

如何避免回调地狱?

可以使用多种技术来避免回调地狱,如下所示。

  1. 使用promise
  2. 借助 async-await
  3. 使用 async.js 库

使用 Async.js 库

让我们谈谈怎样用 async.js 库避免回调地狱。

根据 async.js 官方网站的描述:Async 是一个工具模块,它提供了直接、强大的函数来使用异步 JavaScript。

Async.js 总共提供约 70 个函数。现在,我们将仅讨论其中两个,即 async.waterfall() 和 async.series()。

async.waterfall()

当你要一个接一个地运行某些任务,然后将结果从上一个任务传到下一个任务时,这个函数非常有用。它需要一个函数“任务”数组和一个最终的“回调”函数,它会在“任务”数组中所有的函数完成后,或者用错误对象调用“回调”之后被调用。

  1. var async = require('async'); 
  2. async.waterfall([ 
  3.     function(callback) { 
  4.       /*   
  5.         Here, the first argument value is null, it indicates that 
  6.         the next function will be executed from the array of functions. 
  7.         If the value was true or any string then final callback function 
  8.         will be executed, other remaining functions in the array  
  9.         will not be executed. 
  10.       */ 
  11.         callback(null, 'one', 'two'); 
  12.     }, 
  13.     function(param1, param2, callback) { 
  14.         // param1 now equals 'one' and param2 now equals 'two' 
  15.         callback(null, 'three'); 
  16.     }, 
  17.     function(param1, callback) { 
  18.         // param1 now equals 'three' 
  19.         callback(null, 'done'); 
  20.     } 
  21. ], function (err, result) { 
  22.     /* 
  23.       This is the final callback function. 
  24.       result now equals 'done' 
  25.     */ 
  26. }); 

async.series()

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读