Express 为我提供了一个空数组。在 ipfs 函数中调用 Push。日志工作正常

Express provides me with an empty array. Push is called in an ipfs function. Log works fine

router.post('/up', verify, async (req, res) => {
if (req.files.upload.length > 0) {
    var result = [];
    
    req.files.upload.forEach((uploadFile) => {
        ipfs.add(Buffer.from(uploadFile.data), function (err, upfile) {
            if (err) {
                console.log(err)
            } else {
                // THIS WORK
                console.log({ "name": uploadFile.name, "cid": upfile[0].path });

                // THIS NOT
                result.push({ "name": uploadFile.name, "cid": upfile[0].path });
            }
        })
    });

    res.send(result);
}});

我得到一个空的结果。我该如何解决?原因是什么?不是很懂...

您在循环内调用的异步 ipfs.add 函数是异步的。因此 res.send() 那些调用返回之前 执行。

下面是一个异步方法的示例,用于并行(或至少并行)执行多个 ipfs.add 调用,同时将结果收集到一个数组中。

(async () => {

  const content = [ 
    'a', 'b', 'c' 
  ]

  const results = await Promise.all(
    content.map(async (item) => await ipfs.add(item))
  )

  console.log(results)
})()

因此对于您的代码,类似这样的内容 - 虽然您需要重新添加错误检查并像以前一样格式化 return 对象。扩展地图功能以提高可读性。

const result = await Promise.all(
  req.files.upload.map(async (uploadFile) => {
    return await ipfs.add(Buffer.from(uploadFile.data));
  })
)

res.send(result);