tips

作者: black白先森 | 来源:发表于2018-04-28 17:12 被阅读2次

    // 1. 对于事件循环的每个阶段(定时器队列,I/O 事件队列,immediates 队列,close 处理队列是 4 个主要阶段),
    // 2. 事件循环在移动到某一阶段之前,Node 会检查 nextTick 队列中是否有可处理的事件。
    // 3. 如果有,在前往下一个主要阶段之前,事件循环会先直接处理这个队列直至它为空(当然还有其他 microtask 队列)。

    // 但 immediates 队列被确保会在事件循环的 I/O 阶段之后被立即执行
    setImmediate(() => console.log('this is set immediate 1'));
    setImmediate(() => console.log('this is set immediate 2'));
    setImmediate(() => console.log('this is set immediate 3'));

    // 当事件循环开始执行的时候,Node 首先会处理定时器队列。接着,在处理完 I/O 之后,会来到 immediates 队列
    setTimeout(() => console.log('this is set timeout 1'), 0);
    setTimeout(() => {
    console.log('this is set timeout 2');
    process.nextTick(() => console.log('this is process.nextTick added inside setTimeout'));
    }, 0);
    setTimeout(() => console.log('this is set timeout 3'), 0);
    setTimeout(() => console.log('this is set timeout 4'), 0);
    setTimeout(() => console.log('this is set timeout 5'), 0);

    //
    process.nextTick(() => console.log('this is process.nextTick 1'));
    process.nextTick(() => {
    // 第二次 循环 队头, 第一次 nextTick 队列 队尾
    process.nextTick(console.log.bind(console, 'this is the inner next tick inside next tick'));
    });
    process.nextTick(() => console.log('this is process.nextTick 2'));
    process.nextTick(() => console.log('this is process.nextTick 3'));
    process.nextTick(() => console.log('this is process.nextTick 4'));

    // 1. 不能确定的 setImmediate 与 setTimeout
    // 设定一个 0 秒过期的定时器,永远不能保证在 0 秒后回调会被准时调用
    setTimeout(function() {
    console.log('setTimeout')
    }, 0);
    setImmediate(function() {
    console.log('setImmediate')
    });

    // 2. 能 保证 setTimeout 执行后于 setImmediate
    // due 在处理完 I/O 之后,会来到 immediates 队列
    /**
    const fs = require('fs');

    fs.readFile(__filename, () => {
    // 此 setTimeout 是被放到 下一轮 时间循环
    setTimeout(() => {
    console.log('timeout')
    }, 0);
    setImmediate(() => {
    console.log('immediate')
    })
    });
    */

    相关文章

      网友评论

          本文标题:tips

          本文链接:https://www.haomeiwen.com/subject/cczglftx.html