-2

I can't seem to find a way to access a value from an async value as it always returns undefined, I would like to wait for the function to end and then retrieve the value but it's not working...

  async UploadFile(file): Promise<any> {

      let ipfsId: any
      const fileStream = fileReaderPullStream(file)
      await this.ipfs.add(fileStream, { progress: (prog) => console.log(`received: ${prog}`) })
      .then((response) => {
        ipfsId = response[0].hash
        console.log(ipfsId)
        return ipfsId
        //window.open("localhost:8080/ipfs/" + ipfsId);
        //window.open("https://ipfs.io/ipfs/" + ipfsId);
      }).catch((err) => {
        console.error(err)
      }) 

  }

And this is my call:

  uploadFile(event) {

    const fileSelected: File = event.target.files[0];
    (async() => {
    this.temp_ipfs_hash = await this.IPFS.UploadFile(fileSelected)
    .then((response) => console.log(response))
    console.log(this.temp_ipfs_hash)
    })()

  }

I'd like to access the return value but it's always returning me undefined or error value... Anyone has any idea what I could try here ?

Thank you so much for your time! :)

Edit: I had no idea it was wrong to post images, so sorry, I've changed it! sorry! :(

2 Answers2

0
  • UploadFile should return a promise, it's currently returning nothing. In order to chain promises, you should replace the last line by

    return this.ifps.add(...).then(...).catch(...);


  • Alternative using await: return await which is the result value returned by the promise

    return await this.ifps.add(...).then(...).catch(...);

    In the caller, you can log the result as if there was no promise:

    console.log(this.UploadFile(fileSelected));

Mendy
  • 7,612
  • 5
  • 28
  • 42
Benjamin Caure
  • 2,090
  • 20
  • 27
0

You are using both promise based then and async await simultaneously, your upload file function should either return a promise and then resolve reject it appropriately or if you want to stick to async-await mechanism then your upload file function will have to changed. Here is how async await should be used, assume that foobar is an asynchronous function like your ipfs.add

async function foo() {
  let results = await foobar();
  return results;
}

Here is how you will call such foo

async function bar() {
  let fooResults = await foo();
  console.log(fooResults);
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95