首页 > 解决方案 > 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 个摄像头模块,但为了便于理解,我给出了一个包含两个摄像头模块的示例代码。

标签: node.jsraspberry-piaxios

解决方案


您可以使用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));


推荐阅读