I'm kind of stuck trying to do some async in NodeJS for the first time. I read a bit about Promises and async/await but still confused what would be the best to do in my case where one async function is inside the other.
function startTheater(sourceAudioFile) {
decodeSoundFile(sourceAudioFile).then((result) => {
setLight(); //this has to run only run after decodeSoundFile is complete
});
}
function decodeSoundFile(soundfile) {
return new Promise(function(resolve, reject) {
fs.readFile(soundfile, function(err, buf) {
if (err) throw err
context.decodeAudioData(buf, function(audioBuffer) {
playSound();
findPeaks(pcmdata, samplerate); <<<<<< this function itself has has to finish before decodeSoundFile returns <<<<<<
if (lightPlant.length != 0) {
resolve("light plan populated");
} else {
reject(new Error("broke promise. unable to populate"));
}
}, function(err) {
throw err
})
})
});
}
The following function takes a while to complete but the above decodeSoundFile
returns before it's completion. How do I prevent that when decodeSoundFile
itself is a promise?
function findPeaks(pcmdata, samplerate) {
var interval = 0.5 * 1000;
var step = samplerate * (interval / 1000);
//loop through sound in time with sample rate
var samplesound = setInterval(function() {
if (index >= pcmdata.length) {
clearInterval(samplesound);
console.log("finished sampling sound"); <<this is where decodeSoundFile is good to return after findPeaks execution.
}
for (var i = index; i < index + step; i++) {
max = pcmdata[i] > max ? pcmdata[i].toFixed(1) : max;
}
prevmax = max;
max = 0;
index += step;
}, interval, pcmdata);
}
How do I do this chain this execution in the right way?