【发布时间】:2021-08-22 11:17:04
【问题描述】:
我第一次尝试在 NodeJS 中做一些异步操作时有点卡住了。我阅读了一些关于 Promises 和 async/await 的内容,但仍然对在一个异步函数位于另一个异步函数内部的情况下最好的做法感到困惑。
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
})
})
});
}
以下函数需要一段时间才能完成,但上面的decodeSoundFile 在完成之前返回。当decodeSoundFile 本身就是一个承诺时,我该如何防止这种情况发生?
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);
}
我如何以正确的方式执行此链接?
【问题讨论】:
-
这里有一些关于您发布的代码的奇怪之处。在 decodeSoundFile: 1. 什么是
audioBuffer- 你永远不会使用它。 2. 什么是lightPlant、pcmdata、samplerate——它们不知从何而来。 - 在 findPeaks 中: 1.pevmax是什么 - 它无处不在 -
抱歉,我只是想简短地回答我正在处理的所有音频复杂问题。这就是那些孤立变量的来源。
-
不用放,只是觉得奇怪:p只要知道是什么,不影响答案
标签: javascript node.js promise