0
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);
}});

I get an empty result. How can I fix it? And what is the reason? I don't really understand it ...

Kyrill
  • 265
  • 1
  • 7
  • 19
  • Your code works fine, nothing is wrong with `result.push`, Since `ipfs.add` is async, `res.send` doesn't wait for it's execution and sends the empty result array. – Shivam Mar 24 '21 at 00:56

1 Answers1

1

The async ipfs.add function you are calling inside the loop is asynchronous. So res.send() is executed before those calls come back.

Here's an example of an async approach to execute the multiple ipfs.add calls in parallel (or at least parallelish), while gathering the results into a single array.

(async () => {

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

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

  console.log(results)
})()

So with your code, something like this - although you need to add error checking back in and format the return object as you had before. Map function expanded for readability.

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

res.send(result);
Dietrich Ayala
  • 921
  • 6
  • 9