js promise 模式的 异步回调函数

  //constructor
        var Promise = function() {
            this.callbacks = [];
        }

        Promise.prototype = {
            constructor: Promise,
            resolve: function(result) {
                this.complete("success", result);
            },

            reject: function(result) {
                this.complete("fail", result);
            },

            complete: function(type, result) {
                while (this.callbacks[0]) {
                    this.callbacks.shift()[type](result);
                }
            },

            then: function(successHandler, failedHandler) {
                this.callbacks.push({
                    success: successHandler,
                    fail: failedHandler
                });

                return this;
            }
        }
        var pro = new Promise();
        function ddz() {
            setTimeout(function () {
                pro.resolve("将数据返回到then中的success函数");
            },0);
            return pro;
        }
        var test1 = function (re) {
            console.log(re);
            pro.reject(re + "    保留上一个then中的数据,并跑到第二个then中的fail函数中")
        }
        var test2 = function (re) {
            console.log(re);
        }
        ddz().then(test1).then(function(){},test2);//加一个匿名的success函数

运行结果如下:

1、执行ddz函数,由于函数内调用了一个settimeout函数,该函数并不会立即执行,虽然写了0秒后,ddz函数返回一个promise对象

2、该对象又调用then方法,将test1函数添加到callbacks数组中,同时then函数的返回值是promise本身

3、同样的,又调用了then方法将匿名函数和test2添加到callbacks数组中

4、此时同步代码执行完毕,开始执行settime中的代码,此时调用的是resolve函数,因此会执行callbacks【0】中的success,即test1函数,同时将其shift出来,此时test1函数中调用了reject函数

5、执行的是callbacks【0】中的fail函数(此时的callbacks【0】已经不是上次的了,因为已经shift过一次)

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值