【问题标题】:how to push processed data to list and after that send response from express?如何将处理后的数据推送到列表,然后从快递发送响应?
【发布时间】:2020-04-05 19:07:57
【问题描述】:

我正在尝试使用 multer 调整大小并上传多个文件。它正在工作,但问题是当我将数据发回时,它甚至在处理数据之前就已发送。所以我得到一个空列表。我是 nodejs 的新手,在线尝试过解决方案,但找不到适合我的解决方案。谁能帮我解决这个问题?如何在发送响应之前将数据推送到列表中?

代码附在下面...

router.post('/ads/images', upload.array('images',5), async(req,res)=>{
console.log(req.files);

var data = []
await req.files.every(async(file)=>{
    var imageBuffer = await sharp(file.buffer).png().resize({
        width:250,
        fit: sharp.fit.cover,
        position: sharp.strategy.entropy
    }).toBuffer()
    var thumbnailBuffer = await sharp(file.buffer).png().resize({
        width:150,
        height:150,
        fit: sharp.fit.cover,
        position: sharp.strategy.entropy
    }).toBuffer()
    console.log({imageBuffer,thumbnailBuffer});

    data.push({imageBuffer,thumbnailBuffer})
})



console.log(data);

res.send(data)
},(error,req,res,next)=>{
    res.status(400).send({error:error.message})
})

【问题讨论】:

    标签: node.js express asynchronous async-await multer


    【解决方案1】:

    问题在于你的每一个方法。在异步方法中使用常规循环。

    请改用常规的 for 循环,并且只应用一次锐化变换。

    for(let file of req.files) {
       (your code here)
    }
    

    Using async/await with a forEach loop

    【讨论】:

      【解决方案2】:

      您的 await 调用没有做任何事情,因为 every 不是异步的。从every 切换到map 然后使用Promise.all(..) 等待map 返回的所有promise 完成:

      await Promise.all(req.files.map(async(file) => {
        // ...
      }))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-23
        • 2021-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多