Search code examples
javascriptpromisees6-promise

How to resolve array of promises?


I have a problem with my array of promises.

const customs = this.state.customElements.map(async el => {
      if (el.type === 'paragraph') {
        return somePlainObject;
      } else {
        //uploading an image
        await axios.post(url, el.image, {
          headers: {
            'Content-Type': el.image.type
          }
        });
        return someObject;
      }
    });

And this returns me an array of promises. I'm trying to resolve them using Promise.all() but it doesn't seem to work.

Promise.all(customs).then(() => {
      console.log('then', customs);
      const objectForDatabase = {
        title: this.state.inputs.title,
        subTitle: this.state.inputs.subTitle,
        content: this.state.inputs.content,
        mainImg: uploadConfig.data.url,
        customs
      };
      console.log('object for database', objectForDatabase);
    });

Both console.logs in then are still loggging array of promises. Why does that happen?


Solution

  • The result from the promises are passed as an argument to the callback function of .then(), but you are not using it. Try something like this:

    Promise.all(customs).then((results) => {
          console.log('then', results);
          // ...
    });