美文网首页
js原生实现promise

js原生实现promise

作者: SailingBytes | 来源:发表于2020-05-18 19:13 被阅读0次

Promise构造函数接受一个函数作为参数,函数里面有两个参数resolve和reject分别作为执行成功或者执行失败的函数。

通过then设置操作成功之后的操作,接受两个函数作为参数。

function _Promise() {

            this.status = 'pending';

            this.msg = '';

            var cb = arguments[0];

            var that = this;

            cb(function() {

                that.status = 'resolve';

                that.msg = arguments[0];

            }, function() {

                that.status = 'reject';   

                that.msg = arguments[0];         

            });

            return this;

        }

        _Promise.prototype.then = function() {

            if (this.status == 'resolve') {

                arguments[0](this.msg);

            }

            if (this.status == 'reject' && arguments[1]) {

                arguments[1](this.msg);

            }

        }

        //实例话

        var promise = new _Promise(function(resolve, reject) {

            resolve('success');

        });

        promise.then(function(data) {

            console.log(data);

        }, function(err) {

            console.log(err);

        });

相关文章

网友评论

      本文标题:js原生实现promise

      本文链接:https://www.haomeiwen.com/subject/mcupohtx.html