Promise 原理解析

Promise 是 JavaScript 中处理异步操作的核心机制之一。自 ES6 引入以来,它极大简化了回调地狱(Callback Hell)问题,使异步代码更清晰、可读、可维护。

什么是 Promise?

Promise 是一个表示异步操作最终完成或失败的对象。它有三种状态:

一旦状态从 Pending 变为 Fulfilled 或 Rejected,就不可再更改。

Promise 的基本用法

const promise = new Promise((resolve, reject) => {

  // 异步操作

  setTimeout(() => {

    const success = true;

    if (success) {

      resolve('操作成功');

    } else {

      reject('操作失败');

    }

  }, 1000);

});



promise

  .then(result => console.log(result))

  .catch(error => console.error(error));

链式调用与 then 的返回值

每个 .then() 方法都会返回一个新的 Promise,使得可以链式调用。如果在 then 中返回一个普通值,下一个 then 会接收到该值;如果返回一个 Promise,则会等待其完成后再继续。

手写简易 Promise(符合 Promise/A+ 规范)

理解原理最好的方式是自己实现。以下是一个简化版的 Promise 实现:

class MyPromise {

  constructor(executor) {

    this.state = 'pending';

    this.value = undefined;

    this.reason = undefined;

    this.onFulfilledCallbacks = [];

    this.onRejectedCallbacks = [];



    const resolve = value => {

      if (this.state === 'pending') {

        this.state = 'fulfilled';

        this.value = value;

        this.onFulfilledCallbacks.forEach(fn => fn());

      }

    };



    const reject = reason => {

      if (this.state === 'pending') {

        this.state = 'rejected';

        this.reason = reason;

        this.onRejectedCallbacks.forEach(fn => fn());

      }

    };



    try {

      executor(resolve, reject);

    } catch (err) {

      reject(err);

    }

  }



  then(onFulfilled, onRejected) {

    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;

    onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; };



    const promise2 = new MyPromise((resolve, reject) => {

      if (this.state === 'fulfilled') {

        setTimeout(() => {

          try {

            const x = onFulfilled(this.value);

            resolve(x);

          } catch (e) {

            reject(e);

          }

        }, 0);

      }

      if (this.state === 'rejected') {

        setTimeout(() => {

          try {

            const x = onRejected(this.reason);

            reject(x);

          } catch (e) {

            reject(e);

          }

        }, 0);

      }

      if (this.state === 'pending') {

        this.onFulfilledCallbacks.push(() => {

          setTimeout(() => {

            try {

              const x = onFulfilled(this.value);

              resolve(x);

            } catch (e) {

              reject(e);

            }

          }, 0);

        });

        this.onRejectedCallbacks.push(() => {

          setTimeout(() => {

            try {

              const x = onRejected(this.reason);

              reject(x);

            } catch (e) {

              reject(e);

            }

          }, 0);

        });

      }

    });



    return promise2;

  }

}

总结

Promise 通过状态管理与链式调用机制,为 JavaScript 提供了强大而优雅的异步解决方案。深入理解其内部原理,有助于写出更健壮、高效的异步代码,并为学习 async/await 打下坚实基础。