链接promises实现给出已经解决的错误

时间:2017-03-27 10:57:05

标签: javascript

我一直试图将承诺链接如下,

 doAsyncWork(123)
   .then(function (result){
        return doAnotherAsync();})
   .then(function (result2){
         return displayText(result2)}

function doAsyncWork(value){
     return new Promise(function(resolve, reject){
                var time  = setTimeOut(function (){
                    resolve(value)}, Math.random * 1000);
                 });
      }

 function doAnotherAsyn(){
       return new Promise(function(resolve, reject){
                  var time = setTimeOut(function (){
                      resolve(456)}, Math.random * 100);
        });}

输出是:

123

未定义

未捕获错误:承诺已经解决

在上面的代码中创建的Promises对象实现为。

Promise = (function()
{/**
 * Promise Status Enumerator
 * @private
 */
var Status = {
    Pending: 0,
    Resolved: 1,
    Rejected: 2
};

var Promise = function (fn) {
    /**
     * @private
     * @type {Status}
     */
    this.status = Status.Pending;
    /**
     * @private
     * @type {object}
     */
    this.result = undefined;
    /**
     * @private
     * @type {object}
     */
    this.reason = undefined;
    /**
     * @private
     * @type {Array}
     */
    this.queue = [];

    if (typeof fn !== "function") {
        reject.call(this, new Error('invalid executor'));
    }

    try {//catch errors
        fn.call(null, resolve.bind(this), reject.bind(this));
    } catch (e) {
        reject.call(this, e);
    }
};


Promise.prototype = {
    /**
     * Appends fulfillment and rejection handlers to the promise and return
     * a new promise object
     */
    then: function (onResolved, onRejected) {
        if (this.status === Status.Resolved) {
            return new Promise(function (resolve, reject) {
                resolve(isFunction(onResolved) ? onResolved.call(null, this.result) : undefined);
            }.bind(this));
        }

        if (this.status === Status.Rejected) {
            return new Promise(function (resolve, reject) {
                reject(isFunction(onRejected) ? onRejected.call(null, this.reason) : undefined);
            }.bind(this));
        }

        if (this.status === Status.Pending) {
            //pending
            var instance = this;
            return new Promise(function (resolve, reject) {
                //run resolve or reject object when parent's resolve or reject is called
                instance.queue.push({
                    resolve: function (result) {
                        resolve(isFunction(onResolved) ? onResolved.call(null, result) : undefined);
                    },
                    reject: function (reason) {
                        reject(isFunction(onRejected) ? onRejected.call(null, reason) : undefined);
                    }
                });
            });
        }
    },

    /**
     * Appends a rejection handler callback to the promise and returns a new promise resolving to the return value
     * of the callback
     *
     * @param {?function(error)} onRejected called if the promise is rejected
     */
    catch: function (onRejected) {
        return this.then(undefined, onRejected);
    }
};
/**
 * internal resolve function,simply assigns the result to the promise object
 * @private
 * @param {object} result
 */
function resolve(result) {

    var self = this;
    if (self.status !== Status.Pending) {
        throw "The Promise has already been resolved.";
    }

    if(result instanceof  Promise){

        self.result = result.then(function(innerResult){
            resolve(innerResult).bind(self);
            self.status = Status.Pending;
        });
    }
    else{
        this.result = result;
        this.status = Status.Resolved;
    }

    //call the queued listeners
    this.queue
        .map(function (item) {
            return item.resolve;
        })
        .forEach(function queueResolver(resolver) {
            resolver.call(null, result);
        });

    //delete queue
    this.queue = [];
}

我遵循承诺A + spec来写这个。如果我没有解决任何规范,请告诉我。 请帮助我理解

1.内部承诺的状态如何(在doAnotherAsyn()中)改变为在我的代码中解决,当它应该挂起时。

2.我们如何在链接承诺概念中区分外部和内部承诺对象?

3.我注意到了"结果2"在上面的代码中是一个promise对象,它应该是在函数内创建的内部promise的解析结果。我该如何解决这些问题?

0 个答案:

没有答案