Search code examples
reactjsasync-awaites6-promise

Only reload page if all records have been processed


I'm processing quite a bit of data but for some reason the page reloads before the post and puts can all be processed. There are about 2k records I need to either update or create, but when the process starts it handles a good chunk but then reloads the page... I know it has something to do with how I'm handling the Promises and my async/awaits. Can someone provide some insight into what I'm doing wrong here?

  ...
  // This is called via a button click
  const submitData = async () => {
     await updateRecords(existData)
     await createRecords(newData)
     await setCompleteStatus(true) // I think this might be part of the issue. How do I trigger this after the two previous async function complete?
   }

  // updates records
  const updateRecords = async (data) => {
    const location = dataSet === 'hfc' ? 'measurements' : 'metrics'
    const recordLength = data.length
    // If the object exists, update it via API
    if (recordLength > 0) {
      for (let i = 0; i < recordLength; i += 100) {
        const requests = data.slice(i, i + 100).map((row) => {
          return puts({ row, location }) 
            .catch(e => console.log(`Error updating record: ${row} - ${e}`))
        })
      }
    }
  }

  // creates records
  const createRecords = async (data) => {
    const location = dataSet === 'hfc' ? 'measurements' : 'metrics'
    const recordLength = data.length
    // If the object exists, update it via API
    if (recordLength > 0) {
      for (let i = 0; i < recordLength; i += 100) {
        const requests = data.slice(i, i + 100).map((row) => {
          return posts({ row, location }) 
            .catch(e => console.log(`Error creating record: ${row} - ${e}`))
        })
      }
    }
  }
 
  // api put request
  const puts = async ({ row, location }) => {
    const endpoint = `/api/${location}/record/${row.id}/`
    await axios.put(endpoint, row)
  }

  // api post request
  const posts = async ({ row, location }) => {
    const endpoint = `/api/${location}/create`
    await axios.post(endpoint, row)
  }

  // I'd like for the page to be redirected after all records have been processed
  if (completeStatus) {
    window.location.href = '/portal/'
  }
...

Solution

  • You need to resolve array of promises, as map function return promise.

    const updateRecords = async(data) => {
      const location = dataSet === 'hfc' ? 'measurements' : 'metrics'
      const recordLength = data.length
      // If the object exists, update it via API
      if (recordLength > 0) {
        for (let i = 0; i < recordLength; i += 100) {
          const requests = await data.slice(i, i + 100).map((row) => { //Added await here
            return puts({
                row,
                location
              })
              .catch(e => console.log(`Error updating record: ${row} - ${e}`))
          });
          await Promise.all(requests); // Use this to await all the promises
        }
      }
    }
    // creates records
    const createRecords = async(data) => {
      const location = dataSet === 'hfc' ? 'measurements' : 'metrics'
      const recordLength = data.length
      // If the object exists, update it via API
      if (recordLength > 0) {
        for (let i = 0; i < recordLength; i += 100) {
          const requests = await data.slice(i, i + 100).map((row) => { //added await here
            return posts({
                row,
                location
              })
              .catch(e => console.log(`Error creating record: ${row} - ${e}`))
          });
          await Promise.all(requests); // Use this to await all the promises
        }
      }
    }