美文网首页
Deferred vs Promise

Deferred vs Promise

作者: monvhh | 来源:发表于2018-11-06 23:48 被阅读0次

    如需深入,参考http://liubin.org/promises-book/#promise-library
    以下为个人简单粗暴版理解

    1。 Deferred 是Promise的super,包含Promise,操作Promise;
    2。 Deferred 的写法:不用将代码嵌套在new Promise()中,就像await的方式。如下示例
    Deferred 版

    function Deferred() {
        this.promise = new Promise(function (resolve, reject) {
            this._resolve = resolve;
            this._reject = reject;
        }.bind(this));
    }
    Deferred.prototype.resolve = function (value) {
        this._resolve.call(this.promise, value);
    };
    Deferred.prototype.reject = function (reason) {
        this._reject.call(this.promise, reason);
    };
    function getURL(URL) {
        var deferred = new Deferred();
        var req = new XMLHttpRequest();
        req.open('GET', URL, true);
        req.onload = function () {
            if (req.status === 200) {
                deferred.resolve(req.responseText);
            } else {
                deferred.reject(new Error(req.statusText));
            }
        };
        req.onerror = function () {
            deferred.reject(new Error(req.statusText));
        };
        req.send();
        return deferred.promise;
    }
    

    Promise 版

    function getURL(URL) {
        return new Promise(function (resolve, reject) {
            var req = new XMLHttpRequest();
            req.open('GET', URL, true);
            req.onload = function () {
                if (req.status === 200) {
                    resolve(req.responseText);
                } else {
                    reject(new Error(req.statusText));
                }
            };
            req.onerror = function () {
                reject(new Error(req.statusText));
            };
            req.send();
        });
    }
    

    相关文章

      网友评论

          本文标题:Deferred vs Promise

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