zoukankan      html  css  js  c++  java
  • 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

    工欲善其事,必先利其器
  • 相关阅读:
    Android之JSON格式数据解析
    SSH面试题锦集
    Mysql
    (二)Java基础巩固
    (一)Java基础巩固
    (五)Oracle函数 序列 约束 索引
    让css初学者抓狂的属性float
    微信小程序(4)--二维码窗口
    微信小程序(3)--页面跳转和提示框
    微信小程序(2)--下拉刷新和上拉加载更多
  • 原文地址:https://www.cnblogs.com/ccbest/p/10845536.html
Copyright © 2011-2022 走看看