2026/1/11 23:52:32
网站建设
项目流程
长沙培训网站建设,国家企业公示系统,哈尔滨模板建站软件,滨州百姓网免费发布信息1.then()在 JavaScript 中#xff0c; then() 是Promise 对象的核心方法#xff0c;用于指定异步操作成功后的回调函数#xff0c;也是 fetch 、Promise 链式调用的关键#xff0c;常和 catch() 、 finally() 配合处理异步流程。一、 then() 基本语法javascript
pr…1.then()在 JavaScript 中 then() 是Promise 对象的核心方法用于指定异步操作成功后的回调函数也是 fetch 、Promise 链式调用的关键常和 catch() 、 finally() 配合处理异步流程。一、 then() 基本语法javascriptpromise.then(onFulfilled[, onRejected]);- onFulfilled Promise 状态变为 fulfilled 成功时执行的回调函数接收异步操作的返回值作为参数。- onRejected 可选Promise 状态变为 rejected 失败时执行的回调函数接收错误信息作为参数通常更推荐用 catch() 单独处理错误。二、核心特性链式调用then() 执行后会返回一个新的 Promise 对象因此可以连续调用 then() 实现异步操作的依次执行上一个 then() 的返回值会作为下一个 then() 的参数。javascript// 基础链式调用示例new Promise((resolve) {setTimeout(() resolve(10), 1000);}).then((num) {console.log(num); // 10return num * 2; // 返回值传递给下一个then}).then((num) {console.log(num); // 20return num 5;}).then((num) {console.log(num); // 25});三、 then() 在 fetch 中的应用fetch 返回 Promise 对象因此通过 then() 链式处理响应解析和数据处理是最常见的用法javascriptfetch(https://jsonplaceholder.typicode.com/todos/1)// 第一个then解析响应为JSON格式返回新的Promise.then((response) {if (!response.ok) {throw new Error(HTTP错误${response.status}); // 手动抛出错误触发catch}return response.json();})// 第二个then处理解析后的JSON数据.then((data) {console.log(请求到的数据, data);})// 捕获链式调用中所有的错误.catch((error) {console.error(请求失败, error);});fetch(请求地址).then(json方法).then(第二次操作)