435240
学习node.js stream工作原理过程中,在stream.readable中看到如下一段代码:
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if (((state.pipesCount === 1 && state.pipes === dest) ||
(state.pipesCount > 1 && state.pipes.indexOf(dest) !== -1)) &&
!cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
虽然看了increasedAwaitDrain变量上的注释,但还是不能理解这个变量的作用,Node.js是单线程的,那么对于下面的这三行同步代码:
increasedAwaitDrain = false;
var ret = dest.write(chunk); // dest.write中有异步逻辑,但是同步返回
if (false === ret && !increasedAwaitDrain)
- 第一行
increasedAwaitDrain赋值成false - 第二行执行同步代码
var ret = dest.write(chunk); - 第三行在if中用到了
increasedAwaitDrain这个变量
我理解的是这个变量一定是false,而按照increasedAwaitDrain定义上方的注释,第三行代码中increasedAwaitDrain可能为true?这有点违背我的知识和经验......什么情况下if中increasedAwaitDrain的值为true???
百思不得解,望高手帮忙解答,感激不尽!!!