0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Marking your function `async` doesn't change *when it's called*. The reader won't call it until the load ends, which is after your `uploadFile` function has already returned. – T.J. Crowder Feb 28 '21 at 14:37
  • That's because of asynchronousity, you'll need to make sure that you're done with loading i.e. first reader.onloadend needs to be computed and then you can return the fileAdedd.cid value. – Helper Feb 28 '21 at 14:37
  • What is that `Buffer`? I know of the one fro Node.js, but this clearly isn't Node.js code... – T.J. Crowder Feb 28 '21 at 14:40
  • Since `uploadFile` is an `async` function, you could use use the [`arrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/arrayBuffer) method that `File` inherits from `Blob`. It returns a promise, so you can `await` it: `uploadFile = async (file) => { const { ipfs } = this; this.file = file; const buffer = Buffer.from(await file.arrayBuffer()); const fileAdded = await ipfs.add({ content: buffer }); return fileAdded.cid; };` https://pastebin.com/K9Y9RqfK (I also fixed the `fileAdedd` typo that was at the end of the function.) – T.J. Crowder Feb 28 '21 at 14:42
  • @Helper Thank you for replying, what could be a solution for waiting until the load has been completed? – Filippo Scaramuzza Feb 28 '21 at 14:51
  • @T.J.Crowder Thank you for replying, I've tried your solution and it's working perfectly! Thak you again! – Filippo Scaramuzza Feb 28 '21 at 14:52
  • 1
    @T.J.Crowder very fast, thanks though! :) – Helper Feb 28 '21 at 14:53

0 Answers0