• 001--Node.js之EventLoop


    The event loop is what allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.

    详情见下图

    我们都知道JS是单线程的,当一个任务进入Node.js解释器的执行栈后,会首先看是同步还是异步代码,同步会推入主线程进行解释,异步代码会推入eventLoop事件循环中,这些任务会分为宏任务或者微任务,当执行栈中没有同步代码时,会先执行宏任务:主体script,setTimeout,setInterval,后执行微任务Promise.then,process.nextTick

    console.log('script start');
    
    setTimeout(function() {
      console.log('setTimeout');
    }, 0);
    
    Promise.resolve().then(function() {
      console.log('promise1');
    }).then(function() {
      console.log('promise2');
    });
    
    console.log('script end');
    //script start
    //script end
    //promise1
    //promise2
    //setTimeout
    setTimeout(() => {
    
        // 宏任务
        new Promise(resolve => {
            console.log('promise')
            resolve();
        }).then(() => {
            //微任务
            console.log('then')
        });
    
        // 宏任务
        console.log('宏任务',1);
        // 宏任务
        setTimeout(() => {
    
            console.log('setTimeout',1)
    
        }, 1000);
    
    }, 1000);
    2
    // promise
    //宏任务 1
    //then
    //setTimeout 1
    console.log('script start');
    
    setTimeout(function() {
        
        new Promise((resolve)=>{}).then()
    
        setTimeout(function() {
        
        }, 0);
    
    }, 0);
    
    new Promise(resolve => {
        console.log('promise start');
        setTimeout(() => {
            console.log('setTimeout2');
            resolve();
        }, 1000)
    }).then(function() {
      console.log('promise1');
    }).then(function() {
      console.log('promise2');
    });
    
    console.log('script end');
    //script start
    // promise start
    // script end
    // setTimeout2
    // promise1
    // promise2

     2019-05-10  17:11:45

    工欲善其事,必先利其器
  • 相关阅读:
    Hbase集群部署及shell操作
    sqoop部署与使用
    azkaban部署
    Hive入门操作
    Hive部署
    MapReduce过程详解(基于hadoop2.x架构)
    MapReduce编程中常用的字符操作
    【图文详解】深入HDFS原理
    vue项目跨域问题的解决:vue-cli 开启代理
    beego框架入门(2)
  • 原文地址:https://www.cnblogs.com/ccbest/p/10845536.html
Copyright © 2020-2023  润新知