返回

小试牛刀:亲自动手实现EventLoop

前端

EventLoop 简介

EventLoop 是 Javascript 中一个重要的概念,它负责处理事件和执行任务。EventLoop 是一种消息队列,当有新的事件或任务需要处理时,EventLoop 将它们放入消息队列中。EventLoop 会不断地从消息队列中取出任务并执行,直到队列为空。

宏任务和微任务

宏任务和微任务是 Javascript 中的两种任务类型。宏任务是指需要花费较长时间执行的任务,例如 HTTP 请求、定时器等。微任务是指需要花费很短时间执行的任务,例如 promise 的回调函数、mutation observer 的回调函数等。

宏任务和微任务的执行顺序是:先执行所有宏任务,再执行所有微任务。

EventLoop 循环机制

EventLoop 的循环机制如下:

  1. 检查消息队列中是否有任务需要执行。
  2. 如果有,则取出队列中的第一个任务并执行。
  3. 执行完任务后,检查消息队列中是否有新的任务需要执行。
  4. 重复步骤 1 和 2,直到消息队列为空。

手写 Promise 源码

// Promise 构造函数
function Promise(executor) {
  this.state = 'pending'; // 初始状态为 pending
  this.value = undefined; // 初始值 undefined
  this.reason = undefined; // 初始原因 undefined
  this.onFulfilledCallbacks = []; // 存放成功回调的数组
  this.onRejectedCallbacks = []; // 存放失败回调的数组

  // 执行器函数
  executor(resolve.bind(this), reject.bind(this));
}

// 成功回调函数
function resolve(value) {
  if (this.state === 'pending') {
    this.state = 'fulfilled';
    this.value = value;
    this.onFulfilledCallbacks.forEach(callback => callback(value));
  }
}

// 失败回调函数
function reject(reason) {
  if (this.state === 'pending') {
    this.state = 'rejected';
    this.reason = reason;
    this.onRejectedCallbacks.forEach(callback => callback(reason));
  }
}

// then 方法
Promise.prototype.then = function(onFulfilled, onRejected) {
  if (this.state === 'pending') {
    this.onFulfilledCallbacks.push(onFulfilled);
    this.onRejectedCallbacks.push(onRejected);
  } else if (this.state === 'fulfilled') {
    onFulfilled(this.value);
  } else if (this.state === 'rejected') {
    onRejected(this.reason);
  }
};

// catch 方法
Promise.prototype.catch = function(onRejected) {
  return this.then(undefined, onRejected);
};

结语

通过本文,你已经对 EventLoop 的执行原理有了深入的了解。你不仅掌握了宏任务和微任务的概念,还学会了如何实现一个简单的 EventLoop。相信这些知识能帮助你写出更高效、更健壮的代码。