0

I am trying to use promises and async functions to send chunks of an array to an api call that inserts them into a DB. I am trying to get the top function to chunk the array and await for the backend to finsih then it will move on to the next chunk. It errors out after the first iteration. Any ideas??

async chunkArray(arr) {
   let len = arr.length
   let update_arr
   let i = 1
   for(i; i<=len; i++) {
     if((i%125) === 0) {
       update_arr = arr.slice(i-125,i)

       await this.updateChuckArray(update_arr)
     } else if(i === len) {
       let div = (Math.floor(len/125) * 125)
       update_arr = arr.slice(div, len)

       await this.updateChuckArray(update_arr)
     }
   }
},

updateChuckArray(update) {
  return new Promise(resolve => {
    this.$http.put(`/route`, update).then(res => {
      res.data.error ? this.$root.updateError(res.data.error) : this.$root.updateSuccess(res.data.message)
    }).catch(error => {
        this.$root.updateError(res.data.error)
      })
  })
}
Houshman85
  • 72
  • 6
  • How does it "error out"? – Ilmari Karonen Nov 29 '19 at 21:34
  • I'm getting request entity is too large, I am trying to send array chucks of length 125 – Houshman85 Nov 29 '19 at 21:36
  • The way you're looping over the array and slicing it seems really weird. Why not just [do it like this](https://stackoverflow.com/a/8495740)? I suspect that might resolve your error. You should also try stepping through the loop with a debugger to see exactly what gets sliced off the array at each step. – Ilmari Karonen Nov 29 '19 at 21:40

1 Answers1

1

First off your updateChuckArray() never resolves the promise it returns (you never call resolve()).

Instead of manually wrapping a new promise around your function call (that is a promise anti-pattern), you can just return the promise you already have and write it like this:

updateChuckArray(update) {
    return this.$http.put(`/route`, update).then(res => {
      res.data.error ? this.$root.updateError(res.data.error) : this.$root.updateSuccess(res.data.message);
    }).catch(error => {
        this.$root.updateError(error);
    })
}

FYI, it's unclear what your error handling strategy is. The way you wrote the code (which is followed above), you catch an error from this.$http.put() and handle it and let the loop continue. If that's what you want, this will work. If you want the for loop to abort on error, then you need to rethrow the error in the .catch() handler so the error gets back to the await.

Also, not that in your .catch() handler, you were doing this:

this.$root.updateError(res.data.error)

but there is no res defined there. The error is in error. You would need to use that in order to report the error. I'm not sure what the structure of the error object is here or what exactly you pass to $.root.updateError(), but it must be something that comes from the error object, not an object named res.

jfriend00
  • 683,504
  • 96
  • 985
  • 979