nodejs事件和事件循环简介

前端开发 作者: 2024-08-21 11:20:01
简介 熟悉javascript的朋友应该都使用过事件,比如鼠标的移动,鼠标的点击,键盘的输入等等。我们在javascript中监听这些事件,从而触发相应的处理。 同样的nodejs中也有事件,并且还有

简介

事件

const server = http.createServer((req,res) => {
  res.statusCode = 200
  res.setHeader('Content-Type','text/plain')
  res.end('welcome to www.flydean.com\n')
})
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()
eventEmitter.on('fire',() => {
  console.log('开火')
})

eventEmitter.emit('fire')
eventEmitter.on('fire',who => {
  console.log(`开火 ${who}`)
})

eventEmitter.emit('fire','美帝')
eventEmitter.on('fire',(who,when) => {
  console.log(`开火 ${who} ${when}`)
})

eventEmitter.emit('fire','川建国','now')
eventEmitter.on('fire',when) => {
    setImmediate(() => {
      console.log(`开火 ${who} ${when}`);
  });
})

eventEmitter.emit('fire','川建国','now')

事件循环

const action2 = () => console.log('action2')

const action3 = () => console.log('action3')

const action1 = () => {
    console.log('action1')
    action2()
    action3()
}

action1()
action1
action2
action3
const action2 = () => console.log('action2')

const action3 = () => console.log('action3')

const action1 = () => {
    console.log('action1')
    setTimeout(action2,0)
    action3()
}

action1()
action1
action3
action2
const action2 = () => console.log('action2')

const action3 = () => console.log('action3')

const action1 = () => {
    console.log('action1')
    setTimeout(action2,0)
    new Promise((resolve,reject) =>
        resolve('应该在action3之后、action2之前')
    ).then(resolve => console.log(resolve))
    action3()
}

action1()
action1
action3
应该在action3之后、action2之前
action2
process.nextTick(() => {
  console.log('i am the next tick');
})
setImmediate(() => {
  console.log('I am immediate!');
})
setInterval(() => {
  console.log('每隔2秒执行一次');
},2000)
const id = setInterval(() => {
  console.log('每隔2秒执行一次');
},2000)

clearInterval(id)
const myFunction = () => {
  console.log('做完后,隔2s再次执行!');

  setTimeout(myFunction,2000)
}

setTimeout(myFunction,2000)
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66061.html