0

I have a function that I want to call that returns a promise, but inside the called function I need to iterate over an array of items.

My code is below:

          var playSearchResults = handlerInput => {

             let lJson = constants.RESPONSE;
             lJson.document.mainTemplate.item.items = []; 
             let lResults =[];
             let lVoArtistRecord;
             return new Promise(function (resolve, reject) {
    
               lResults.forEach(async function (voArtist) {
               lVoArtistRecord = await getResponseAudio(...parms);

               if (lVoArtistRecord.found) {

                 lJson.document.mainTemplate.item.items.push({
                    "type": constants.AUDIO_TYPE,
                    "source": lVoArtistRecord.url,
                    "filter": [
                        {
                            "type": "Trim",
                            "start": 0,
                            "end": 30000
                        },
                        {
                            "type": "FadeIn",
                            "duration": 2000
                        },
                        {
                            "type": "FadeOut",
                            "duration": 5000
                        }
                    ]
                  });
            }
           console.log(`..returning response ${JSON.stringify(lJson)}`);
           resolve(lJson);
       });

}

So what I see is that the console.log('.....returning response ... happens before the for-each loop has completed and I do not get a returning data that I can see happening after the resolve.

What I'm looking to do is ensure that the whole for-each loop completes and the resolve sends back data to the calling function.

Ethan Richardson
  • 461
  • 2
  • 10
  • 28
  • 1
    Use `for of` loop instead of `forEach()` method because it doesn't works with promises like you expect it to. – Yousaf Oct 16 '20 at 16:39
  • Please ignore any missed brackets I was copying the code from my IDE piece by piece so I may have missed out closing bracket. – Ethan Richardson Oct 16 '20 at 16:39
  • @Yousaf - will that push each array element on to the lJson array before reaching to the resolve()? This is what I am trying to achieve – Ethan Richardson Oct 16 '20 at 16:47

0 Answers0