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 ...
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);