|
为了在回调的帮助下实现这个功能,代码应该如下所示:
- http.get('https://api.github.com/users', function(users) {
- /* Display all users */
- console.log(users);
- http.get('https://api.github.com/repos/javascript/contributors?q=contributions&order=desc', function(contributors) {
- /* Display all top contributors */
- console.log(contributors);
- http.get('https://api.github.com/users/Jhon', function(userData) {
- /* Display user with username 'Jhon' */
- console.log(userData);
- });
- });
- });
从上面的代码片段中,你可以看到代码变得更加难以理解,以及难以维护和修改。这是由回调函数的嵌套而引发的。
如何避免回调地狱?
可以使用多种技术来避免回调地狱,如下所示。
- 使用promise
- 借助 async-await
- 使用 async.js 库
使用 Async.js 库
让我们谈谈怎样用 async.js 库避免回调地狱。
根据 async.js 官方网站的描述:Async 是一个工具模块,它提供了直接、强大的函数来使用异步 JavaScript。
Async.js 总共提供约 70 个函数。现在,我们将仅讨论其中两个,即 async.waterfall() 和 async.series()。
async.waterfall()
当你要一个接一个地运行某些任务,然后将结果从上一个任务传到下一个任务时,这个函数非常有用。它需要一个函数“任务”数组和一个最终的“回调”函数,它会在“任务”数组中所有的函数完成后,或者用错误对象调用“回调”之后被调用。
- var async = require('async');
- async.waterfall([
- function(callback) {
- /*
- Here, the first argument value is null, it indicates that
- the next function will be executed from the array of functions.
- If the value was true or any string then final callback function
- will be executed, other remaining functions in the array
- will not be executed.
- */
- callback(null, 'one', 'two');
- },
- function(param1, param2, callback) {
- // param1 now equals 'one' and param2 now equals 'two'
- callback(null, 'three');
- },
- function(param1, callback) {
- // param1 now equals 'three'
- callback(null, 'done');
- }
- ], function (err, result) {
- /*
- This is the final callback function.
- result now equals 'done'
- */
- });
async.series()
(编辑:我爱制作网_潮州站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|