我使用 Node js 每隔几秒将来自观察者的数据传递给在数组中存储 id.ts 文件名的函数 Streamplay,这在存储时工作正常,但是当我从程序中的另一个函数回调时,我从该数组中得到未定义的值......并且我无法弄清楚需要如何编写它:
var stream_play = [];
watch('/tmp/1_.m3u8', function(event, name) {
/* DEFINE - variables */
var ts = [];
ts.push(1);
streamplay(id, ts[ts.length-1]);
});
function streamplay(id, ts, callback) {
/* CHECH - ts */
if (ts !== 0) {
console.log('adding id..'+id+'...with ts...'+ts)
stream_play[id] = ts;
} else {
return callback(stream_play[id]);
}
}
并从 Node 中的主函数调用,如下所示:
streamplay(stream, 0, function(response) {
console.log('streaming ts file...'+response+'...to client...')
res.write(fs.readFileSync('/tmp/'+response));
})
我明白了:
streaming ts file...undefined...to client...
最佳答案
您的函数调用 streamplay(stream, 0, function(response) {
将最终陷入 streamplay
中的 else 条件。这一行是 return callback(stream_play[id]);
并且 stream_play
数组已初始化,但为空。访问 JavaScript 数组中不存在的元素将返回 undefined
。
关于javascript - Node 回调数组未定义(空值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46448799/