Search code examples
javascriptreactjsnext.jspromisees6-promise

Looping through array of objects and performing async functions


I am using NextJS and I have an array of assets (images) in my state. I need to post those images to the API. I have an object that does this with the following syntax:

let response = await api_image.post()
if(response.status !== 201) {
    resolve()
}

So for each of the images in the assets array I need to first create a new api_image then post it. I am quite new to promises, and so far from StackOverflow research i have the following code put together:

 async postAssetsToAPI(asset) {
        let registrationID = this.registrationID
        return new Promise(async(resolve, reject) => {
            let api_image = new api_image()
            api_image.filename = asset.filename
            api_image.uploadOwnerType = 'registration'
            api_image.uploadOwnerID = registrationID
            let response = await api_image.post()
            if(response.status !== 201) {
                resolve()
            }
        })
    }

    async redirectToFinish() {

        let registrationID = this.registrationID
        let success = true
    
        console.log('redirectToUploadMetadata')

        const promises = this.props.assets.map(this.postAssetsToAPI)
        await Promise.all(promises).then(
            () => {console.log('promises succeeded')},
            () => {console.log('promises failed')}
        )

    }

This just fails with the console message promises failed. Also, I'm unsure about the async inside new Promise(async(resolve, reject), it feels like im just takking on async wherever to get it to work, but I couldnt have the await inside the promise without it.

Whats the best way to achieve this? I need each api_image to post and save data in the database and for a message to display at the end when its done.


Solution

  • Don't mix and match async with new Promise and then – all you need is

    async function redirectToFinish() {
      const registrationID = this.registrationID;
    
      const uploadPromises = this.props.assets.map(async (asset) => {
        const api_image = new api_image();
        api_image.filename = asset.filename;
        api_image.uploadOwnerType = "registration";
        api_image.uploadOwnerID = registrationID;
        const response = await api_image.post();
        if (response.status !== 201) {
          throw new Error("Error uploading image");
        }
      });
    
      try {
        await Promise.all(uploadPromises);
      } catch (err) {
        console.log(err);
        return;
      }
      console.log("redirectToFinish");
    }