手写promise

在 JavaScript 中,Promise 是一种用于异步编程的对象。它允许你将异步操作的代码写在一起,并在操作完成时得到通知。Promise 的主要作用是使异步操作的代码更具可读性和可维护性,并让你能够更好地控制异步操作的流程。

手写 Promise 的原理其实就是实现了一个类似 Promise 的对象。这个对象能够存储异步操作的状态,并在操作完成时执行注册的回调函数。在这个对象中,通常会包含以下几个重要的属性和方法:

  • state 属性:用于存储异步操作的状态,可以取 "pending"、"fulfilled" 和 "rejected" 三种值。
  • value 属性:用于存储异步操作的结果值。
  • callbacks 数组:用于存储已注册的回调函数。
  • transition 函数:用于更新 statevalue 属性的值。
  • then 方法:用于注册回调函数,并返回一个新的 Promise 对象。

function myPromise(executor) {
  // Store the state of the promise
  let state = "pending";
  // The resolved value of the promise
  let value = undefined;
  // The array of registered callbacks
  let callbacks = [];

  // A function to transition the state of the promise
  function transition(newState, newValue) {
    // Update the state and value
    state = newState;
    value = newValue;
    // Execute any registered callbacks
    if (state === "fulfilled") {
      callbacks.forEach(cb => cb(value));
    }
  }

  // The "then" method of the promise
  function then(onFulfilled) {
    // Return a new promise
    return new myPromise(function(resolve) {
      // Register the callback for the new promise
      callbacks.push(function(value) {
        // Resolve the new promise with the result of the callback
        resolve(onFulfilled(value));
      });
      // If the promise is already fulfilled, execute the callback immediately
      if (state === "fulfilled") {
        resolve(onFulfilled(value));
      }
    });
  }

  // Execute the executor function with the resolve and reject functions
  executor(function(newValue) {
    transition("fulfilled", newValue);
  });

  // Return the "then" method
  return {
    then: then
  };
}

下面我们来看一个使用手写的 myPromise 的示例。在这个例子中,我们实现了一个简单的计时器,它会在指定的时间后触发一个回调函数。

function timer(delay) {
  // Return a new promise
  return new myPromise(function(resolve) {
    // Wait for the specified delay
    setTimeout(function() {
      // Resolve the promise with the current time
      resolve(Date.now());
    }, delay);
  });
}

// Start the timer
timer(1000)
  // Register a callback to print the time
  .then(function(time) {
    console.log(time); // 1603444476266 (current time in ms)
  });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值