Async / Await not working as expected with Promise.all and .map function

I have a variety of functions async

that I am using and I am having a strange problem.

My code working looks like this:

async mainAsyncFunc (metadata) {
  let files = metadata.map(data => this.anotherAsyncFunc(data.url));
  return Promise.all(files);
}

      

Function

anotherAsyncFunc

as follows:

  async anotherAsyncFunc (url) {
    return await axios({
      url,
    }).then(res => res.data)
      .catch(err => {
      throw err;
    });
  }

      

My problem occurs when I try to add more data to what the first function ( mainAsyncFunc

) returns . My thoughts are to do it in map

, naturally, and when all is said and done, the change will look like this:

async mainAsyncFunc (metadata) {
    files = metadata.map(data => {
        return new Promise((resolve) => {
          let file = this.anotherAsyncFunc(data.download_url);
          let fileName = data.name;
          resolve({
            file,
            fileName
          });
        });
      });
    return Promise.all(files);
}

      

If it is not clear, I get the file as normal and append filename to it, then solving this object.

For some reason, this returns pending promises, whereas I expect it to wait for them to complete and then be returned as the complete file and name in the object. Any help understanding what I am doing wrong would be greatly appreciated.

+3


source to share


2 answers


It looks like you solved your problem, just like a little pointer, you can simplify your code even further like this:



async anotherAsyncFunc (url) {
    return (await axios({ url })).data;
}

async mainAsyncFunc (metadata) {
    let files = metadata.map(async data => ({
        file: await this.anotherAsyncFunc(data.download_url),
        fileName: data.name
    }));

    return Promise.all(files);
}

      

+5


source


Just solved the problem:

  files = metadata.map(async (data) => {
    let file = await this.anotherAsyncFunction(data.download_url);
    let fileName = data.name;
    return {
      file,
      fileName
    };
  });

      



I needed to wrap the anonymous function in async

so that I could use await

inside it. Hope this helps someone else with a similar problem!

+1


source







All Articles