Axios 0.21.0 版本引入了 Promise.allSettled() 方法,用于等待所有请求成功或失败,并返回一个数组,包含每个请求的结果。但是在实际使用中,我们可能会遇到一些问题。
例如,当使用 Promise.allSettled() 方法时,如果其中一个请求失败了,整个数组会被标记为失败,并抛出异常,导致其他请求无法继续执行。
为了解决这个问题,我们可以使用 Promise.all() 方法代替 Promise.allSettled() 方法,并在 catch 语句中捕获异常,并使用 Promise.resolve() 方法将异常转换为普通值,使得整个数组可以正常输出结果。
示例代码如下:
const axios = require('axios');
const urls = ['https://url1.com', 'https://url2.com', 'https://url3.com'];
Promise.all(
urls.map(url =>
axios.get(url).catch(error => {
return Promise.resolve(error);
})
)
)
.then(results => {
console.log(results);
})
.catch(error => {
console.log(error);
})
在上面的代码中,我们首先将所有的 URL 存储在一个数组中,然后使用 Promise.all() 方法来发起所有请求。在发送请求时,我们使用 catch 语句来捕获异常,并使用 Promise.resolve() 方法将异常转换为普通值。最后,我们使用 then() 方法来输出整个数组的结果。
使用这种方法,我们可以轻松地处理请求失败的情况,并获取整个数组的返回结果。