为什么setTimeout在我的流实现中以这种方式运行?

问题描述 投票:0回答:2

此代码的最后一行成功调用节点中自定义Duplex流的_read方法。

const timeContext = new TimeContext(sampleRate);
const input = new InputStream(timeContext); // Stream.Readable
const throttle = new Throttle(sampleRate); // Stream.Transform

const stackSource = [];

const stack = new StackStream(stackSource); // Stream.Duplex

input.pipe(throttle).pipe(stack);

stack.read(); // This will call the _read method of StackStream

添加setTimeout以延迟stream.read()调用,setTimeout的回调不会被调用:

const timeContext = new TimeContext(sampleRate);
const input = new InputStream(timeContext); // Stream.Readable
const throttle = new Throttle(sampleRate); // Stream.Transform

const stackSource = [];

const stack = new StackStream(stackSource); // Stack.Duplex

input.pipe(throttle).pipe(stack);

setTimeout(() => {
    stack.read(); // This callback never gets called
}, 1000);
javascript settimeout node-streams
2个回答
0
投票

它肯定会被调用,但其他东西是错误的

setTimeout(() => {
    console.log('We got here');
    stack.read(); // This is what is crashing in your code
    console.log('We don\'t get here');
}, 1000);

它只是没有你期望的行为,因为发生了一些其他错误。查看控制台以查看引发的错误。


0
投票

看起来,read()函数是堆栈对象的局部属性,而setTimeout无法看到堆栈对象的这个局部属性。这就是为什么它以这种方式表现的原因。

请参考此解决方案以供参考

https://stackoverflow.com/a/4536268/10371717

© www.soinside.com 2019 - 2024. All rights reserved.