I have two functions: one plays audio, another one async function that should run after. I should run this sequence N times.
But the problem is it runs in parallel. When the audio start playing second function also runs.
The question is: how to run this functions consequently? The second function should run when the audio is finished.
const [song] = useState(typeof Audio !== 'undefined' && new Audio())
function playSong(songNum) {
song.src = songs[songNum]
song.play()
}
async function finalFunction() {
for (let i = 0; i < songs.length; i++) {
playSong(i)
await secondFunction().then((res) => {
console.log(res)
})
}
}
I tried to add promise, but it didn’t help, it only runs the first function.
function playSong(songNum) {
return new Promise(() => {
song.src = songs[songNum]
song.play()
})
}
async function finalFunction() {
for (let i = 0; i < songs.length; i++) {
await playSong(i).then(() =>
secondFunction().then((res) => {
console.log(res)
}),
)
}
}
3
Answers
Not a complete solution, but a starting point to get you on the right track. You will need to adjust it a bit to make it work for your specific use case and incorporate additional functions if you want to.
The idea is to to create a playback chain using a promise and the ended event to wait for the sound to play.
The
playInSequence
function then recursively calls itself, until there are no songs left. You can also wait for another promise before continuing with the playback.You need to make your finalFunction a promise because it’s asynchronous.
You can extract all your logic all into one function then make your finalFunction a promise, and then run your code how many times you need to.
Something like this: