I'm trying to get more confident with async/await and event handler in Javascript and React.
More precisely I have this function:
uploadFile = async (file) => {
const { ipfs } = this;
this.file = file;
let buffer;
var fileAdded;
let reader = new window.FileReader();
reader.readAsArrayBuffer(file);
reader.onloadend = async () => {
buffer = await Buffer.from(reader.result)
fileAdded = await ipfs.add({ content: buffer });
}
return fileAdedd.cid;
}
After I run this function I get:
Unhandled Rejection (TypeError): Cannot read property 'cid' of undefined
meaning that fileAdded
is not actually modified.
Obviously I've tried moving the return statement inside the event handler and it worked but I need it outside because I call this function from another with await
and with the return inside the handler it doesn't wait for the value to be returned. What theoretical concept am I missing? How can I modify the fileAdded
value and access it from outside the event handler?