黑马学习笔记_Promise.all 静态方法
-
概念:合并多个 Promise 对象,等待所有同时成功完成(或某一个失败),做后续逻辑

-
语法:
const p = Promise.all([Promise对象, Promise对象, ...]) p.then(result => { // result 结果: [Promise对象成功结果, Promise对象成功结果, ...] }).catch(error => { // 第一个失败的 Promise 对象,抛出的异常对象 })

Promise.all([Promise对象, Promise对象, ...])
all()括号内要求为可迭代的。
-
例题需求:同时请求“北京”、“上海”、“广州”、“深圳”的天气并在网页尽可能同时显示

-
核心代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Promise的all方法</title> </head> <body> <ul class="my-ul"></ul> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> /** * 目标:掌握Promise的all方法作用,和使用场景 * 业务:当我需要同一时间显示多个请求的结果时,就要把多请求合并 * 例如:默认显示"北京", "上海", "广州", "深圳"的天气在首页查看 * code: * 北京-110100 * 上海-310100 * 广州-440100 * 深圳-440300 */ // 1. 请求城市天气,得到Promise对象 const bjPromise = axios({ url: 'http://hmajax.itheima.net/api/weather', params: { city: '110100' } }) const shPromise = axios({ url: 'http://hmajax.itheima.net/api/weather', params: { city: '310100' } }) const gzPromise = axios({ url: 'http://hmajax.itheima.net/api/weather', params: { city: '440100' } }) const szPromise = axios({ url: 'http://hmajax.itheima.net/api/weather', params: { city: '440300' } }) // 2. 使用Promise.all,合并多个Promise对象 const p = Promise.all([bjPromise, shPromise, gzPromise, szPromise]) p.then(result => { // 注意:结果数组顺序和合并时顺序是一致 console.log(result) const htmlStr = result.map(item => { return `<li>${item.data.data.area} --- ${item.data.data.weather}</li>` }).join('') document.querySelector('.my-ul').innerHTML = htmlStr }).catch(error => { console.dir(error) }) </script> </body> </html>
【TIPS】
写太多 axios 过于繁琐,可以改为下面的代码。
const cities = ['110100', '310100', '440100', '440300'] const promises = cities.map(city => { return axios({ url: 'http://hmajax.itheima.net/api/weather', method: 'GET', params: { city } }) }) const p = Promise.all(promises) p.then(res => { console.dir(res) const htmlStr = res.map(item => { return `<li>${item.data.data.area} —— ${item.data.data.weather}</li>` }).join('') document.querySelector('.my-ul').innerHTML = htmlStr }).catch(error => { console.dir(error) })
Q: Promise.all 什么时候使用?
A: 合并多个 Promise 对象并等待所有同时成功的结果,如果有一个报错就会最终为失败状态。当需要同时渲染多个接口数据到网页上时使用
1181

被折叠的 条评论
为什么被折叠?



