购物网站管理层,建筑考试,全国最大网站建站公司,WordPress怎么添加音乐目录 一#xff1a;promise对象是什么
二#xff1a;语法#xff08;Promise使用步骤#xff09;
三#xff1a;Promise-三种状态 一#xff1a;promise对象是什么
Promise 对象代表异步操作最终的完成#xff08;或失败#xff09;以及其结果值。
即Promise对象是…目录 一promise对象是什么
二语法Promise使用步骤
三Promise-三种状态 一promise对象是什么
Promise 对象代表异步操作最终的完成或失败以及其结果值。
即Promise对象是用来管理一个异步操作最终状态和结果值(then、catch)的对象
二语法Promise使用步骤
//1.创建Promise对象
const p new Promise((resolve,reject){
//2.执行异步任务-并传递结果
//成功调用resolve(值)方法并触发then()执行
//失败调用reject(值)方法并触发catch()执行
})
//3.接收结果
p.then(result{
//成功
}).catch(error{
//失败
})
三Promise-三种状态
一个Promise对象必然处于以下几种状态之一
待定(pending):初始状态既没有兑现也没有拒绝已兑现(fulfilled):操作成功完成已拒绝(rejected):操作失败
Promise对象一旦被兑现/拒绝两种状态中一种设置就无法再更改状态 四Promise.all
Promise.all用于合并多个Promise对象等待所有Promise对象中请求同时成功或某一个失败后再做后续逻辑
流程图如下 语法
const p Promise.all([Promise对象,Promise对象,....])
p.then(result{//result结果:[Promise对象成功结果Promise对象成功结果....]
}).catch(error{//第一个失败的Promise对象抛出的异常
})
同时查询北京、上海、广州、深圳四地天气
!DOCTYPE html
html langenheadmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0titlePromise的all方法/title
/headbodyul classmy-ul/ulscript srchttps://cdn.jsdelivr.net/npm/axios/dist/axios.min.js/scriptscript/*** 目标掌握Promise的all方法作用和使用场景* 业务当我需要同一时间显示多个请求的结果时就要把多请求合并* 例如默认显示北京, 上海, 广州, 深圳的天气在首页查看* code* 北京-110100* 上海-310100* 广州-440100* 深圳-440300*/const bObj axios({ url: https://hmajax.itheima.net/api/weather, params: { city: 110100 } })const sObj axios({ url: https://hmajax.itheima.net/api/weather, params: { city: 310100 } })const gObj axios({ url: https://hmajax.itheima.net/api/weather, params: { city: 440100 } })const szObj axios({ url: https://hmajax.itheima.net/api/weather, params: { city: 440300 } })const p Promise.all([bObj, sObj, gObj, szObj])p.then(result {// console.log(result);const Str result.map(element {return li${element.data.data.area}--${element.data.data.weather}/li}).join()document.querySelector(.my-ul).innerHTML Str}).catch(error {console.dir(error)})/script
/body/html