你不知道的Event Loop

本文深入探讨JavaScript的EventLoop机制,详细解释了宏任务与微任务的执行顺序,通过实例解析了异步操作的流程。理解这一机制对于优化JavaScript代码和提升应用性能至关重要。同时,文章以一个具体的代码示例展示了EventLoop在实际场景中的应用。

没有特别的幸运,那么就特别的努力!!!

Eventloop的作用

Eventloop解决javaScript单线程运行时不会阻塞的一种机制

Eventloop事件循环

事件队列在同步完成后,首先执行nextTick,等nextTick执行完成后,会先执行micro task,等micro task队列空了之后,才会执行macro task。(如果中间添加了micro task加入micro task队列,会继续去执行micro task队列,然后再回到macro task队列)

简讲

主线程(宏任务) => 微任务 => 宏任务 => 主线程

在这里插入图片描述
栈(zhan) —— 后进先出
一种挤压式,先进去的被挤压到栈底 读取时数据时从栈顶开始


线性数据结构,二叉树方式维护

队列 —— 先进先出
因为队列只允许一端插入,另一端删除

宏任务

script全部代码、setTimeout、setInterval、setImmediate(浏览器暂时不支持,只有IE10支持,具体可见MDN)、I/O、UI Rendering。

微任务

Process.nextTick(Node独有)、Promise、Object.observe(废弃)、MutationObserver

举个例子

简化

async function f() {
  await p
  console.log('ok')
}

等同于

function f() {
  return RESOLVE(p).then(() => {
    console.log('ok')
  })
}

深化

console.log('script start')

async function async1() {
  await async2()
  console.log('async1 end')
}
async function async2() {
  console.log('async2 end') 
}
async1()

setTimeout(function() {
  console.log('setTimeout')
}, 0)

new Promise(resolve => {
  console.log('Promise')
  resolve()
})
  .then(function() {
    new Promise(resolve => {
      console.log('Promise4')
      resolve()
    }).then(function() {
       console.log('Promise5') 
    })
    console.log('promise1')
  })
  .then(function() {
    console.log('promise2')
  })

console.log('script end')
  • 首先,打印script start,调用async1()时,返回一个Promise,所以打印出来async2 end
  • 每个 await,会新产生一个promise,但这个过程本身是异步的,所以该await后面不会立即调用。
  • 继续执行同步代码,打印Promisescript end,将then函数放入微任务队列中等待执行。
  • 同步执行完成之后,检查微任务队列是否为null,然后按照先入先出规则,依次执行。
  • 回到await的位置执行返回的 Promise 的 resolve 函数,打印async1 end
  • 执行打印Promise4 (如果中间添加了micro task加入micro task队列,会继续去执行micro task队列,然后再回到macro task队列)
  • 将then函数放入微任务队列中等待执行,所以接下来打印promise1
  • 再打印Promise5
  • 然后执行打印promise5,此时then的回调函数返回undefinde,此时又有then的链式调用,又放入微任务队列中,再次打印promise2
  • 当微任务队列为空时,执行宏任务,打印setTimeout

希望能帮助到大家,同时祝愿大家在开发旅途中愉快!!!

拿着 不谢 请叫我“锤” !!!

An event loop is a programming construct that allows for the handling of asynchronous operations in a program. It works by waiting for and dispatching events or messages in a program. Specifically, an event loop listens for events, such as user input or network requests, and then calls the appropriate callback function to handle the event[^1]. In the context of programming, especially in languages that support asynchronous programming like Python, the event loop is crucial for managing multiple operations without blocking the execution of the program. When an event occurs, the event loop picks it up and executes the associated handler. This is particularly useful in applications that require high concurrency, such as web servers or GUI applications, where the program must respond to various inputs and events from users or external systems[^1]. For example, in a web browser, the event loop handles user interactions like clicks and keystrokes, as well as rendering updates and network requests. Similarly, in a server-side application, the event loop can manage multiple client connections and process their requests efficiently without the need for multi-threading. The event loop operates on a single thread, using non-blocking I/O calls, which means that it can handle many simultaneous connections and operations without the overhead of thread management. This model is often more efficient and simpler to manage than traditional multi-threaded approaches, which can suffer from issues such as race conditions and deadlocks[^1]. To illustrate, consider a simple server that needs to handle multiple client requests. Instead of creating a new thread for each client, which can be resource-intensive and complex to manage, the server can use an event loop to handle each request asynchronously. When a client sends a request, the event loop schedules the request to be processed, and once the processing is complete, the result is sent back to the client. In summary, the event loop is a fundamental concept in asynchronous programming, enabling programs to handle multiple tasks concurrently and efficiently, making it possible to build scalable and responsive applications. ```python import asyncio async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message} from {addr}") print("Send: %r" % message) writer.write(data) await writer.drain() print("Close the client socket") writer.close() async def main(): server = await asyncio.start_server( handle_client, '127.0.0.1', 8888) addr = server.sockets[0].getsockname() print(f'Serving on {addr}') async with server: await server.serve_forever() asyncio.run(main()) ``` The code above demonstrates a simple asynchronous server using Python's `asyncio` library, which utilizes an event loop to handle multiple client connections concurrently.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值