- Objective: - Breadcrumb: # 概念阐释 ## 语义 因为[[js 异步 Promise.then()方法]]会返回一个promise对象,所以使用链式调用可以避免传统[[JavaScript 异步编程]]中的多层嵌套。 `promise.then()`在处理异步操作**相互依赖**或**执行顺序**重要的情况的好方法。 链式调用代替了[[js Iterators Callback Functions 回调函数|回调函数]],使代码更加简洁。 ## 语法 ```js doSomething() .then((firstValue) => { return doSoncendSomething(firstValue)})//firstValue是doSomething的resolve值 .then((secondValue) => { return doThirdThing(secondValue)})//secondValue是doSecondSomething的resolve值 .then((finalResult) => { console.log(`Got the final result: ${finalResult}`);// finalResult是doThirdThing的resolve值 }) .catch((failureCallback)=>{console.log(failureCallback)});//所有reject值 ``` - `doSomething`,`doSoncendSomething`,`doThirdThing`的函数参数,分别是上一个函数的resolvresolve值 # 实例 - 同时获得[[response]]状态和JSON格式的响应数据 ```js //1. 调用 `fetch()` API,并将返回值赋给 `fetchPromise` 变量,发起获取资源的请求。 const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json'); //2. promise.then()方法,将在fetch成功时,返回一个新的promise对象 //3. response.json将返回一个promise对象,resolved时将响应体解析为json格式 fetchPromise .then( response => { return response.json(); }) //4. 当reponse.json返回的promise对象resolved了,这个回调函数会接收到解析后到json数据,并打印出内容中的第一个json数据 .then( json => { console.log(json[0].name); }); ``` #### 输出结果 ``` “baked beans”(“products.json”中第一个产品的名称) ``` - [[js 异步 Promise 链式调用练习 - 支付流程]] ![](http://image.harryrou.wiki/2023-09-08-CleanShot%202023-09-08%20at%2009.19.31%402x.png) # 相关内容 链式调用就像堆积木,你首先做一件事(选择绿色的积木),然后在那件事的基础上继续做下一件事(叠放蓝色的积木),然后再继续做下一件事(叠放红色的积木),依此类推。 # 参考资料 - [Fetch API的response接口](https://developer.mozilla.org/zh-CN/docs/Web/API/Response)