Wait for JavaScript programme to finish running before continuing


I am trying to run a for each loop which goes through each item in the data table and runs a JavaScript code for that list item, however, I am unable to make the For Each loop wait until the JavaScript programme is finished. I am running this on Mobile. 

Thank you for the help! 

Try to add $resolve as last statement in your JavaScript code. This will automatically make a promise of your code.

What do you mean with not able to make the for each wait untill the JavaScript? Do you get any error? Can you paste the error here? Can you share more details about what your JavaScript code is doing on each item?

I am trying to run a youtube video for each item in the data table one after the other, I am using a for each loop to go through each item and pass the video id into the javascript which runs the video. However, I am unable to make the 'for each' loop wait until the video is over before going to the next item in the list. 

I am not getting any errors however it is just running through the loop without waiting for the javascript to finish, I also tried adding a sleep function in the javascript however it still doesn't work. 

And what do you mean by "run the video"? Do you have an iframe with the video within it, or any other kind of component?