node.js - Axios - 等待所有响应运行 .then 块
问题描述
我想做什么?
我一直在尝试使用树莓派相机模块拍摄图像并将其发送回控制器 pi。
我使用 axios 同时向多个摄像头模块发送来自控制 pi 的获取请求。拍摄图像后,将其压缩并发回。
app.get('/shoot', (req,res) => {
//Get request for images without projection
axios.all([
axios.get("http://192.168.43.100:3000/capture", {
headers: {
Accept: 'application/zip',
},
responseType: 'arraybuffer',
}),
axios.get("http://192.168.43.102:3000/capture", {
headers: {
Accept: 'application/zip',
},
responseType: 'arraybuffer',
})
]).then(axios.spread((response1, response2) => {
//saving to local storage
fs.writeFileSync(`./img/cam01${now}.zip`,response1.data)
fs.writeFileSync(`./img/cam02${now}.zip`,response2.data)
res.render('final', {
cam01:`cam01: ${response1.statusText}`,
cam02:`cam02: ${response2.statusText}`
})
})).catch(error => {
console.log(error)
})
})
我面临的问题..
我注意到的一个问题是 axios 正在等待所有响应以保存收到的文件。在这种情况下,响应 1 和响应 2。
如果两个摄像头模块都工作正常,则没有问题。但如果其中一个失败,控制器将不会保存文件。
有没有一种方法可以在收到回复时保存每个回复?
注意: 我有 10 个摄像头模块,但为了便于理解,我给出了一个包含两个摄像头模块的示例代码。
解决方案
您可以使用Promise.allSettled
来获取每个Promise
结果的状态。
您可以在此链接上找到更多详细信息
Promise.allSettled([
Promise.resolve(33),
new Promise(resolve => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error('an error'))
])
.then(values => console.log(values));
推荐阅读
- javascript - Puppeteer 使用 window.find 并单击一个元素
- python-3.x - 如何在同一个 SCL shell 中安装 Python3 和 GCC 7?
- c# - REST API 身份验证有什么不同?
- hive - 从一个 Hive 查询中获取多个根阶段
- python - 使用 unoconv 从 pptx 转换为 pdf 的问题
- laravel - 如何将视频保存到 Tinymce 上的 Laravel 存储文件夹
- vb.net - 有关 SSRS 中使用的函数的文档
- java - 更新文件时在 Dropbox API 中保留区分大小写的文件名
- javascript - 如何将数组从 django 视图传递到图表的外部 JS 文件
- python - 将 XML 标头和 doctype 导出到 XML 文件