Promise 简单实现

/**
 * Created by wikid on 3/6/17.
 */
;(function (f) {
    /**
     * 模块 引入方式
     */
    if (typeof exports === 'object') module.exports = f();
    else if (typeof define === 'function' && define.amd) define(f);
    else if (typeof window !== undefined) window.Promise = f();
})(function () {
    function Promise(fn) {
        /*
            value: resolve 的结果值(主要要来传递)
            state: promise 的状态
                    1. pending  等待中
                    2. fulfilled 已完成
                    3. rejected 失败
            deferred: resolve 的回调栈
         */
        var value = null,
            state = 'pending',
            deferreds = [];

        /**
         * 为了兼容 promise 的串行,所以同一 then 方法同一返回 Promise 类型的实例
         * @param fulfilledCall
         * @param rejectedCall
         * @returns {Promise}
         */
        this.then = function (fulfilledCall, rejectedCall) {
            /**
             *  每一次调用 then 方法时,都会创建一个 bridge promise
             */
            return new Promise(function (resolve) {
                handle({
                    fulfilledCall: fulfilledCall || null,
                    rejectedCall: rejectedCall || null,
                    resolve: resolve,
                    reject: reject
                })
            });
        };

        function handle(deferred) {
            if (state === 'pending') {
                deferreds.push(deferred);
                return;
            }

            var cb = state === 'fulfilled' ? deferred.fulfilledCall : deferred.rejectedCall,
                ret;
            // 兼容异常处理
            if (cb === null) {
                cb = state === 'fulfilled' ? deferred.resolve : deferred.reject;
                cb(value);
                return
            }

            try {
                ret = cb(value);
                deferred.resolve(ret);
            } catch (e) {
                deferred.resolve(e);
            }
        }

        function resolve(newValue) {
            //
            if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
                var then = newValue.then;
                if (typeof then === 'function') {
                    then.call(newValue, resolve, reject);
                    return;
                }
            }

            state = 'fulfilled';
            value = newValue;
            finale();
        }

        function reject(reason) {
            state = 'rejected';
            value = reason;
            finale();
        }

        function finale() {
            /**
             * 异步执行,主要是兼容,创建 promise 实例时,fn 内直接将 promise 的状态置为 fulfilled,
             * 而 后面的 then 方法还未执行,从而导致 deferreds 为 空数组
             */
            setTimeout(function () {
                deferreds.forEach(function (deferred, i) {
                    deferred(value);
                });
            }, 0)
        }

        fn(resolve);
    }

    return Promise;
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Promise是一种用于处理异步操作的JavaScript对象。它提供了一种更优雅和可读性更高的方式来处理异步代码,避免了回调地狱的问题。Promise有三个状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。当Promise的状态发生改变时,会触发相应的回调函数。 以下是一个简单Promise实现原理的例子: ```javascript class MyPromise { constructor(executor) { this.status = 'pending'; this.value = undefined; this.reason = undefined; this.onResolvedCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.status === 'pending') { this.status = 'fulfilled'; this.value = value; this.onResolvedCallbacks.forEach((callback) => callback()); } }; const reject = (reason) => { if (this.status === 'pending') { this.status = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach((callback) => callback()); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value; onRejected = typeof onRejected === 'function' ? onRejected : (reason) => { throw reason; }; const promise2 = new MyPromise((resolve, reject) => { if (this.status === 'fulfilled') { setTimeout(() => { try { const x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } if (this.status === 'rejected') { setTimeout(() => { try { const x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } if (this.status === 'pending') { this.onResolvedCallbacks.push(() => { setTimeout(() => { try { const x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); }); this.onRejectedCallbacks.push(() => { setTimeout(() => { try { const x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); }); } }); return promise2; } resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError('Chaining cycle detected for promise')); } if (x instanceof MyPromise) { x.then(resolve, reject); } else { resolve(x); } } catch(onRejected) { return this.then(null, onRejected); } } ``` 这个例子展示了一个简单Promise实现,包括Promise的构造函数、状态的改变、回调函数的执行、链式调用以及错误处理等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值