Wait for the callback

I have an array with audio files to play all one at a time. I am using a javascript player that will play audio and will provide a callback upon completion.

for (i = 0; i < audioFiles.length; i++) { PlayAudio(audioFiles[i], function(){ alert('complete file #' + i); }); } 

But now my problem is how to do this one at a time. The above snippet will start several audio files and play them in parallel. What is the best solution - wait until the callback is called?

+5
source share
3 answers

There are many solutions. Waiting for a callback to work seems like a good solution.

 function playAudioFile(index) { PlaidAudio(audioFiles[index], function () { var next = index + 1; if (next < audioFiles.length) { playAudioFile(index+1); } }); } function playAudioFiles() { playAudioFile(0); } 

Side note:

If you're looking for a more general way to run tasks in batches, you should look at promises here , here, or here (although the last post only applies to AngularJS).

+5
source

Yoy can use an asynchronous library. Thus, I solve every problem with asynchrony. In this case, you can use the "every" sentence:

 async.each( // List of item audioFiles, // Function to apply to each item function(index, callback){ PlayAudio(audioFiles[index], function(){ callback() }); }, // Function callback function(err,results){ alert("Process finished"); } ); 

And if you want to avoid parallelism, you can use "eachSeries" instead of "each"

 async.eachSeries( // List of item audioFiles, // Function to apply to each item function(index, callback){ PlayAudio(audioFiles[index], function(){ callback() }); }, // Function callback function(err,results){ alert("Process finished"); } ); 

https://github.com/caolan/async

0
source

You can use a combination of Promises and generators to achieve what you want. Using a combination of Promises and generators will allow you to wait for the completion of each file before playing the next, leaving the stream open for interaction with the user or whatever you want.

This article has a good background to start with.

-1
source

Source: https://habr.com/ru/post/1235559/


All Articles