looping over an array asynchronously and then resolving a promise from a function

26 Views Asked by At

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.

0

There are 0 best solutions below