JavaScript (ES2015) – Handling Promises in a loop (full working example)

I’ve spent the best part of the last day and half working with a simple Promise problem in JavaScript.

The scenario I have is:

  • I have a tree structure of folders (and sub-folders) with documents in them.
  • The production scenario I’m emulating is to submit each item in the tree (both folders and documents) to an API for saving, and to receive a return object with a new ID.
  • Documents are are associated with folders via IDs (e.g. Document.FolderID = Folder.ID and Folder.ParentID = Folder.ID).
  • Each item is added to an array of data in my JavaScript app.

The heart of this problem is the asynchronous call to the API. Because I need to associate documents with folders, and sub-folders with parent folders, I need to process each folder and wait for the response to get the new ID before processing sub-items.

Old school, this was done with callback (and I still use callback to this day). But in the interest of staying “modern” I took the ES2015 Promise approach.

Another thing to factor in is the loop through folders and items in the tree. I chose the for(let i; ..; ..) approach to pluck items out of the arrays in the tree. However, you can’t just call the api within the for loop because by the time an async finishes executing and you’re ready to process the next item,. the loop could have iterated on, changed the value of the iterator (i in this example) and hence the currently item in the array.

So you need to wrap the call the API in another function to localise the scope of the variables.

At the end of processing the tree I also need to tell the calling function everything is complete. Which means tracking the completion status of all promises in the loop and notifying the caller of overall completion only once all branches are finished (using Promise.all()).

Anyway, I created a fully working Pen at https://codepen.io/jsnelders/pen/LYVJQbG to demonstrate how this works.
I suggest you pop it open in CodePen itself to see the results – open the browser console (not the CodePen Console) to view debug output.

See the Pen
JavaScript (ES2015) – Handling Promises in a loop
by Jason (@jsnelders)
on CodePen.