1

how can i wait to all axios requests in loop will finish?

this is my code:

  async uploadMedia({ getters, commit }, payload) {
    await commit('setUploadLoading', true)

    const upload = new Promise((resolve) => {
      payload.forEach((item, index) => {
        const form = new FormData()
        form.append('file', payload[index])
        form.append('token', getters.getCustomerToken)
        form.append('no', index)

        this.$axios
          .post(`${process.env.API_URL}/visa/uploadfile`, form, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then(() => resolve())
      })
    })

    await upload.then(() => commit('setUploadLoading', true))
    await upload.finally(() => commit('setUploadLoading', false))
  }

i make 2 requests in this loop, but i don't know how to wait until all requests to finish.

ShaSha
  • 119
  • 6

1 Answers1

1

use Promise.all

 async uploadMedia({ getters, commit }, payload) {
    await commit('setUploadLoading', true)

    const upload = new Promise((resolve) => {
      const unresolvedPromises = [] // array of promises
      payload.forEach((item, index) => {
        const form = new FormData()
        form.append('file', payload[index])
        form.append('token', getters.getCustomerToken)
        form.append('no', index)

        const promise = this.$axios
          .post(`${process.env.API_URL}/visa/uploadfile`, form, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })

        unresolvedPromises.push(promise) // push promise to array

      })
      const resolvedPromises = 
        Promise.all(unresolvedPromises).then(res => console.log(res)) // wait for all promises to be resolved
    })

    await upload.then(() => commit('setUploadLoading', true))
    await upload.finally(() => commit('setUploadLoading', false))
  }

docs: https://developer.mozilla.org/tr/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

obiwankenoobi
  • 1,112
  • 2
  • 14
  • 27