skip to Main Content

I’m attempting to create a function that will execute simultaneously to send images for Cloud Firestore. At the moment I’m attempting to simulate a request with setTimeout to understand how the function works.

Although I can’t seem to get it to work as expected:

const functionO = async () => {
    try {
      console.log('before')
      const datas = [1,2,3]
      await new Promise(async (resolve, reject) => {
        await datas.forEach((d) => {
          // This is simulating a request to firestore cloud
          setTimeout(() => {
            console.log(d)
          }, 1000)
        })
        resolve()       
      })      
      console.log('after')
    } catch (err) {
    }
  }

The output:

before
after
1
2
3

expected (the numbers can be in different orders, although I need to wait for the promise to finish to continue):

before
1
2
3
after

How I intend to use the function later on:

const functionO = async () => {
    try {
      console.log('before')
      const datas = [1, 2, 3]
      await new Promise(async (resolve, reject) => {
        images.forEach(async (image) => {
          const extension = image?.type?.split('/')[1]
          const reference = await storage().ref(
            `receitas/${userInfo?.uid}/uid.${extension}`,
          )
          reference.putFile(file)
        })
        resolve()
      })
      console.log('after')
    } catch (err) {}
  }

The intention is, if something fails on sending a image, it won’t execute the rest of the function.

2

Answers


  1. Chosen as BEST ANSWER

    I believe this is a solution

    try { 
          const images = [{uri: someUri}, {uri: someUri}]
    
          const imagesPromise = await images.map(async (image) => {
            const imageRequest = new Promise<void>((resolve) => {
              const extension = image?.type?.split('/')[1]
              const reference = storage().ref(
                `receitas/${userInfo?.uid}/uid.${extension}`,
              )
              reference.putFile('')
              resolve()
            })
            return imageRequest
          })
    
          await Promise.all(imagesPromise)
    
          console.log('run after promise')
        } catch (error) {
          console.log('Error on submit receita', error)
        }
    

  2. for…each only accepts synchronous functions, it does not work as expected with asynchronous stuff. You need to use a traditional for-loop or for..of.
    I can’t tell you why this is like it is…

    Maybe you can find more information in this thread:
    Using async/await with a forEach loop

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search