- Objective: - Breadcrumb: # 概念阐释 ## 语义 用接近于JS同步编程的方法写[[js 异步 Promise 链式调用]]。 ## 语法 ```js async function asyncAwaitVersion() {   let firstValue = await returnsFirstPromise();   let secondValue = await returnsSecondPromise(firstValue);   let thirdValue = await returnsThirdPromise(secondValue) ;   console.log(thirdValue);//打印最后一个promise的resolve值 } ``` - 第二个函数开始,**链入**上一个Promise返回的resolve值,即上一个**变量名称** # 实例 ```js async function readFiles() { let firstSentence = await promisifiedReadfile('./file.txt', 'utf-8'); let secondSentence = await promisifiedReadfile('./file2.txt', 'utf-8'); console.log(firstSentence, secondSentence); } readFiles(); ``` # 相关内容 ## try...catch 处理reject值 [[js 异步 Promise 链式调用]]是通过`.catch()`来捕获`reject()`的值,在`async...await`中通过`try...catch`来捕获。 ```js let function = async ()=>{ try{ } catch(error){ console.log(error)//捕获第一个错误后,程序将不再继续执行 } } ``` # 问题 1. 阅读[原题](https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-front-end-development/tracks/fscj-22-async-javascript-and-http-requests/modules/wdcp-22-learn-javascript-syntax-async-await-40c16baa-3867-4d62-917d-5b66da1a85f5/lessons/async-await/exercises/multiple-awaits)中的library.js,写一个`makeBeans`的链式调用,并调用(invoke)函数;结果: ```bash $ node app.js I bought fava beans because they were on sale. Time to soak the beans. ... The fava beans are softened. Time to cook the beans. ... The beans are cooked! Dinner is served! ``` 1. 阅读[原题](https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-front-end-development/tracks/fscj-22-async-javascript-and-http-requests/modules/wdcp-22-learn-javascript-syntax-async-await-40c16baa-3867-4d62-917d-5b66da1a85f5/lessons/async-await/exercises/error-handling)写出处理正确和错误的代码 正确的情况 Bean Souffle is served! ```bash $ node app.js Fingers crossed... Putting the Bean Souffle in the oven Dinner is ruined! Ordering a pizza! ``` # 问题答案 ```js let makeBeans = async () => { let type = await shopForBeans(); let isSoft = await soakTheBeans(type);//调用上一个函数参数 let dinner = await cookTheBeans(isSoft);//调用上一个函数参数 console.log(dinner); }; makeBeans(); ``` # 参考资料