0

I am relative new to JS and not being able to apply the promise concept to an use case I have, I checked this SO as others but could not derivate the solution for my case. I need to call promises inside a loop but only after the loop is done the next "then" should be called. Shuold this be possible in JS?

function startCooking(ingredients) {
    Utility.startConnection()
        .then(
            function (connectionTime) {             
                for (let [key, plainVector] of ingredients) {
                    encryptIngredients(plainVector)
                        .then(
                            function (encryptedBinary) {
                                return Utility.cookDinner();
                            }
                        ).then(
                            function (dinner) {                             
                                console.log(...);
                            }
                    );
                }
            }
        ).catch(
            ...
        );              
}

function encryptIngredients() {
    return new Promise(...);
}
David
  • 3,971
  • 1
  • 26
  • 65

1 Answers1

1

This is broadly how this would work.

If this function encrypts a single ingredient:

function encryptIngredient(ingredient) {

   return new Promise(...);

}

Then this function encrypts a list of ingredients:

function encryptIngredients(ingredients) {

   // Note that 'shift' changes the array
   const current = ingredients.shift();
   return encryptIngredient(current).then( () => {
      if (ingredients.length > 0) {
        return encryptIngredients(ingredients);
      }
   });       

}

Here's the async/await version of the last function. It's much simpler:

async function encryptIngredients(ingredients) {

   for(const ingredient of ingredients) {
      await encryptIngredient(ingredient);
   }    

}
Evert
  • 93,428
  • 18
  • 118
  • 189
  • Wow, that brings some light, I will try it out tomorrow, I am using a map, let's see if I can make it work. – David Feb 07 '19 at 22:09
  • The recursive function definitely worked, since I am using a map I needed to use an ugly workaround instead of "shift" using for (let [key, plainVector] of ingredients) { currentKey = key; currentVector = plainVector; break}; ingredients.delete(currentKey); but it works, thanks. – David Feb 08 '19 at 12:44
  • That makes sense @David. It might help to try to write a general function for iterating sequentially over a list of promises and return their result as an array. – Evert Feb 08 '19 at 19:23