匠人学院 JR Academy学AI来匠人
匠人学院 JR Academy学AI来匠人

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png
EN

关于公司

关于我们元宇宙课堂新闻资讯匠人工作成为导师匠人导师联系我们匠人商店J3.Club

匠人资源

工作内推匠人活动1对1私教行业白皮书线上学习平台面试中心分享面试经验Internship会员中心

AI 工具

AI 工具箱考证匠 Cert Master求职匠 Job Hunter牛小匠 UniMate AI

AI 学习方向

全部学习方向AI EngineerContext EngineeringVibe CodingPrompt MasterAI BuilderAI 产品经理Python 入门

AI 应用提效

AI 办公提效AI 数据分析AI 财务AI 内容创作AI 视觉创作前端开发Hermes AgentOpenClaw 本地智能体

大学资源

墨尔本大学昆士兰大学新南威尔士大学悉尼大学莫那什大学阿德莱德大学RMITQUTUTS

少儿 AI 教育

Airbotix 少儿 AI 编程澳洲家长实用资料库NAPLAN 成绩单怎么看My School 学校数据指南悉尼私校学费 2026少儿编程课程与训练营

移民服务

澳洲移民技术移民189/190/491雇主担保482/186/494投资移民188/888英国移民美国移民加拿大移民

企业合作

P3职业孵化器Enterprise (EN)企业培训实习合作招聘合作申请合作

求职代理

岗位代投职位监控LinkedIn代运营LinkedIn人脉代加了解P3项目

匠人支持

FAQsTerms & ConditionsPrivacy PolicyCancellation & Refund PolicySite map

Top Categories

Web全栈班DevOps项目班数据工程全栈班数据分析项目班编程入门班Business Analyst实习算法集训营

求职就业

BA和产品经理实习数据科学实习数据分析实习Marketing实习简历修改面试指导导师指导VIP

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

联系方式

hello@jiangren.com.au0421-672-555

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2026 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572

首页/资源中心/文章详情
JR Academy · Blog职业洞察

Asynchronous JavaScript: From Callback Hell to Async and Await

Asynchronous JavaScript: From Callback Hell to Async and Await.Synchronizing asynchronous tasks in JavaScript was a serious issue for a very long time.

发布日期2018-07-24
阅读时长5 分钟
作者JiangRen Mr

快速导航

  • A Brief History of Asychronous JavaScript
  • Approach 1: Callback Hell (“The Pyramid of Doom”)
  • JavaScript Promises
  • Approach 3: Async/Await
  • Async - A Long Awaited Resolution of a Promise

One of the keys to writing a successful web application is being able to make dozens of AJAX calls per page.

This is a typical asynchronous programming challenge, and how you choose to deal with asynchronous calls will, in large part, make or break your app, and by extension potentially your entire startup.

Synchronizing asynchronous tasks in JavaScript was a serious issue for a very long time.

 

A Brief History of Asychronous JavaScript

The first and the most straightforward solution came in the form of nested functions as callbacks. This solution led to something called callback hell, and too many applications still feel the burn of it.

Then, we got Promises. This pattern made the code a lot easier to read, but it was a far cry from the Don’t Repeat Yourself (DRY) principle. There were still too many cases where you had to repeat the same pieces of code to properly manage the application’s flow. The latest addition, in the form of async/await statements, finally made asynchronous code in JavaScript as easy to read and write as any other piece of code.

Let’s take a look at the examples of each of these solutions and reflect on the evolution of asynchronous programming in JavaScript.

To do this, we will examine a simple task that performs the following steps:

  1. Verify the username and password of a user.
  2. Get application roles for the user.
  3. Log application access time for the user.

Approach 1: Callback Hell (“The Pyramid of Doom”)

The ancient solution to synchronize these calls was via nested callbacks. This was a decent approach for simple asynchronous JavaScript tasks, but wouldn’t scale because of an issue called callback hell.

The code for the three simple tasks would look something like this:

const verifyUser = function(username, password, callback){
   dataBase.verifyUser(username, password, (error, userInfo) => {
       if (error) {
           callback(error)
       }else{
           dataBase.getRoles(username, (error, roles) => {
               if (error){
                   callback(error)
               }else {
                   dataBase.logAccess(username, (error) => {
                       if (error){
                           callback(error);
                       }else{
                           callback(null, userInfo, roles);
                       }
                   })
               }
           })
       }
   })
};

Each function gets an argument which is another function that is called with a parameter that is the response of the previous action.

Too many people will experience brain freeze just by reading the sentence above. Having an application with hundreds of similar code blocks will cause even more trouble to the person maintaining the code, even if they wrote it themselves.

This example gets even more complicated once you realize that a database.getRoles is another function that has nested callbacks.

const getRoles = function (username, callback){
   database.connect((connection) => {
       connection.query('get roles sql', (result) => {
           callback(null, result);
       })
   });
};

In addition to having code that is difficult to maintain, the DRY principle has absolutely no value in this case. Error handling, for example, is repeated in each function and the main callback is called from each nested function.

More complex asynchronous JavaScript operations, such as looping through asynchronous calls, is an even bigger challenge. In fact, there is no trivial way of doing this with callbacks. This is why JavaScript Promise libraries like Bluebird and Q got so much traction. They provide a way to perform common operations on asynchronous requests that the language itself doesn’t already provide.

That’s where native JavaScript Promises come in.

JavaScript Promises

Promises were the next logical step in escaping callback hell. This method did not remove the use of callbacks, but it made the chaining of functions straightforward and simplified the code, making it much easier to read.

Illustration: Asynchronous JavaScript Promises diagram

 With Promises in place, the code in our asynchronous JavaScript example would look something like this:

const verifyUser = function(username, password) {
   database.verifyUser(username, password)
       .then(userInfo => dataBase.getRoles(userInfo))
       .then(rolesInfo => dataBase.logAccess(rolesInfo))
       .then(finalResult => {
           //do whatever the 'callback' would do
       })
       .catch((err) => {
           //do whatever the error handler needs
       });
};

To achieve this kind of simplicity, all of the functions used in the example would have to be Promisified. Let’s take a look at how the getRoles method would be updated to return a Promise:

const getRoles = function (username){
   return new Promise((resolve, reject) => {
       database.connect((connection) => {
           connection.query('get roles sql', (result) => {
               resolve(result);
           })
       });
   });
};

We have modified the method to return a Promise, with two callbacks, and the Promise itself performs actions from the method. Now, resolve and reject callbacks will be mapped to Promise.then and Promise.catch methods respectively.

You may notice that the getRoles method is still internally prone to the pyramid of doom phenomenon. This is due to the way database methods are created as they do not return Promise. If our database access methods also returned Promise the getRoles method would look like the following:

const getRoles = new function (userInfo) {
   return new Promise((resolve, reject) => {
       database.connect()
           .then((connection) => connection.query('get roles sql'))
           .then((result) => resolve(result))
           .catch(reject)
   });
};

Approach 3: Async/Await

JavaScript is asynchronous by default. This might be reason why it took so long to get synchronous-looking code that runs properly in JavaScript. But, better late than never! The pyramid of doom was significantly mitigated with the introduction of Promises. However, we still had to rely on callbacks that are passed on to .then and .catch methods of a Promise.

Promises paved the way to one of the coolest improvements in JavaScript. ECMAScript 2017 brought in syntactic sugar on top of Promises in JavaScript in the form of async and await statements.

They allow us to write Promise-based code as if it were synchronous, but without blocking the main thread, as this code sample demostrates:

const verifyUser = async function(username, password){
   try {
       const userInfo = await dataBase.verifyUser(username, password);
       const rolesInfo = await dataBase.getRoles(userInfo);
       const logStatus = await dataBase.logAccess(userInfo);
       return userInfo;
   }catch (e){
       //handle errors as needed
   }
};

Awaiting Promise to resolve is allowed only within async functions which means that verifyUser had to be defined using async function.

However, once this small change is made you can await any Promise without additional changes in other methods.

Async - A Long Awaited Resolution of a Promise

Async functions are the next logical step in the evolution of asynchronous programming in JavaScript. They will make your code much cleaner and easier to maintain. Declaring a function as async will ensure that it always returns a Promise so you don’t have to worry about that anymore.

Why should you start using the JavaScript async function today?

  1. The resulting code is much cleaner.
  2. Error handling is much simpler and it relies on try/catch just like in any other synchronous code.
  3. Debugging is much simpler. Setting a breakpoint inside a .then block will not move to the next .thenbecause it only steps through synchronous code. But, you can step through await calls as if they were synchronous calls.

 

 

 

 

Front-end
作者JiangRen Mr
一键分享或复制链接
作者: JiangRen Mr查看该作者的更多文章 →

相关学习资源

  • AI 学习中心
  • Prompt 工程入门
  • 前端学习路径
← 上一篇2018年6月30日布里斯班大咖面对面活动集锦下一篇 →IT杂谈|“黑五”明天到,购物不剁手|全澳最全打折信息看这里

相关文章推荐

Atlassian 前端面试流程详细解读

2021-12-10

第一份工作就年薪80k,毫无工作经验的他是怎么做到的?

2019-11-21

如何参与一个顶级开源项目

2019-09-05

如何使用useReducer Hook

2019-09-05

作为一个前端工程师也要掌握的几种文件路径知识

2019-09-05

如何写一个让面试官满意的 Generator 执行器?

2019-09-05
查看全部文章 →
JR Academy
全球华人学习 AI 第一站
✓15000+ 学员
✓50+ 课程
✓AI 驱动学习平台
训练营免费资源AI学习职业辅导
精选推荐
AI 职业影响地图
测测你的职业风险等级,查看转型路径与学习方向
热门工具
AI & 数据训练营
系统化课程 + 真实项目实战,快速提升竞争力
热门课程
1v1 就业辅导
资深导师一对一指导,简历优化 + 面试准备
就业保障
企业内训定制
AI 技能培训方案,助力团队升级
企业服务
热门标签
Vibe CodingAI 编程CursorClaude求职攻略Prompt前端开发后端开发
订阅更新

获取最新 AI 学习资源、技术教程和求职攻略,直接送达邮箱。

我们尊重您的隐私,不会发送垃圾邮件