Await does not wait for IPFS add function.
I am trying to add files to IPFS, then output a JSON of the file name corresponding to the HASH.
But the await just never wait and output an empty file.(Or console log an undefined)
const IPFS = require('ipfs-api');
const ipfs = new IPFS({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' });
const fs = require('fs-extra');
const dir = 'D:/JTEST/';
let nameToHash = new Object();
function writeJSON() {
let output= JSON.stringify(nameToHash);
fs.writeFileSync('output.json', output);
}
async function addFile(data, filename){
await ipfs.add(data, (err, ipfsHash) =>{
console.log(ipfsHash);
nameToHash[filename] = ipfsHash[0]['hash'];
});
}
fs.readdir(dir, async (err, files) => {
if (err)
console.log(err);
else {
for(const file of files){
let data = fs.readFileSync(dir + file);
let a = await addFile(data, file);
console.log(nameToHash); //writeJSON();
}
}
})
From the documentation of ipfs-api
module here: https://www.npmjs.com/package/ipfs-api, I see that many functions of this module use callback style. So it's normal that await
doesn't wait.
In order to use the async/await keyword, you should promisify the callback function. This article might help you understand better: https://flaviocopes.com/node-promisify/