0

Is there a way to add promises to a promise.all after it's started?

If not is there a way I can accomplish the same behavior or am I looking at building out a custom solution?

b.stevens.photo
  • 876
  • 2
  • 9
  • 18
  • 3
    What do you want to achieve? Can you share some code? – Marco Sep 15 '22 at 17:01
  • 3
    You can always `Promise.all` the promise returned by the first call to `Promise.all` with the new Promises `const currentPromiseListPromise = Promise.all([previousPromiseListPromise, ...additionalPromises])` – Jared Smith Sep 15 '22 at 17:02
  • I need to upload compressed media files in the background as they're captured from the camera. It's meant as a backup incase the final upload later fails and we cant get the media. I'm thinking I could keep track of an array of promises, on .then from the last promise create a new promise.all with the current promise array and repeat until the user is finished capturing media. – b.stevens.photo Sep 15 '22 at 17:11

1 Answers1

0

Turns out promises don't work how I thought and they're just a fancy callback system. What I've learned since posting this is that when you call a function that returns a promise the code starts executing immediately and doesn't wait until you await it.

I changed my approach here to collecting the media to be uploaded into an array and when the user exits the camera I loop through the array of media and batch them into a Promise.all, seems to work well!

let copy = [...this.media_to_upload]
this.media_to_upload = [];

while(copy.length){
    await Promise.all( copy.splice(0, 5).map(media => this.MEDIA_EVENT(media) ))
}
b.stevens.photo
  • 876
  • 2
  • 9
  • 18