深入理解 Promise 原理

什么是 Promise?

Promise 是 JavaScript 中用于处理异步操作的对象。它代表一个尚未完成但预期将来会完成的操作,并提供统一的 API 来处理异步结果。

Promise 有三种状态:

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));

Promise 链式调用原理

每次调用 .then().catch() 都会返回一个新的 Promise,从而支持链式调用。 这使得我们可以将多个异步操作串联起来,避免“回调地狱”。

动手演示:运行一个 Promise

点击下面的按钮,查看 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; };



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

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

        setTimeout(() => {

          try {

            let x = onFulfilled(this.value);

            resolve(x);

          } catch (e) {

            reject(e);

          }

        }, 0);

      }

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

        setTimeout(() => {

          try {

            let x = onRejected(this.reason);

            reject(x);

          } catch (e) {

            reject(e);

          }

        }, 0);

      }

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

        this.onFulfilledCallbacks.push(() => {

          setTimeout(() => {

            try {

              let x = onFulfilled(this.value);

              resolve(x);

            } catch (e) {

              reject(e);

            }

          }, 0);

        });

        this.onRejectedCallbacks.push(() => {

          setTimeout(() => {

            try {

              let x = onRejected(this.reason);

              reject(x);

            } catch (e) {

              reject(e);

            }

          }, 0);

        });

      }

    });

    return promise2;

  }

}

总结

Promise 是现代 JavaScript 异步编程的基石。理解其状态机模型、链式调用机制以及错误处理方式, 对编写健壮、可维护的前端代码至关重要。通过本页的学习与实践,希望你能掌握 Promise 的核心原理!