12

我查看了许多实现,它们看起来都非常不同,我无法真正提炼出 Promise 的本质是什么。

如果我不得不猜测它只是一个在回调触发时运行的函数。

有人可以在几行代码中实现最基本的承诺,而无需链接。

例如从这个答案

片段 1

var a1 = getPromiseForAjaxResult(ressource1url);
a1.then(function(res) {
    append(res);
    return a2;
});

函数如何传递才能then知道何时运行。

也就是说,它是如何传递回 ajax 在完成时触发的回调代码的。

片段 2

// generic ajax call with configuration information and callback function
ajax(config_info, function() {
    // ajax completed, callback is firing.
});

这两个片段有什么关系?

猜测:

// how to implement this

(function () {
    var publik = {};
        _private;
    publik.then = function(func){
        _private = func;
    };
    publik.getPromise = function(func){
        // ??
    };
    // ??
}())
4

6 回答 6

27

从根本上说,promise 只是一个对象,它有一个标志,表明它是否已被解决,以及它维护的函数列表以通知它是否/何时被解决。代码有时可以说的不仅仅是文字,所以这里有一个非常基本的、非真实世界的示例,纯粹是为了帮助传达概念:

// See notes following the code for why this isn't real-world code
function Promise() {
    this.settled = false;
    this.settledValue = null;
    this.callbacks = [];
}
Promise.prototype.then = function(f) {
    if (this.settled) {
        f(this.settledValue);                // See notes 1 and 2
    } else {
        this.callbacks.push(f);
    }
                                             // See note 3 about `then`
                                             // needing a return value
};
Promise.prototype.settle = function(value) { // See notes 4 and 5
    var callback;

    if (!this.settled) {
        this.settled = true;
        this.settledValue = value;
        while (this.callbacks.length) {
            callback = this.callbacks.pop();
            callback(this.settledValue);      // See notes 1 and 2
        }
    }
};

所以Promise保存状态,以及当承诺完成时要调用的函数。解决承诺的行为通常在Promise对象本身之外(当然,这取决于实际使用,您可以将它们结合起来——例如,与 jQuery 的ajax[ jqXHR] 对象一样)。

同样,以上内容纯粹是概念性的,并且遗漏了一些重要的东西,这些东西必须存在于任何现实世界的 Promise 实现中才能使其有用:

  1. then并且settle应该始终异步调用回调,即使承诺已经解决。then应该因为否则调用者不知道回调是否是异步的。settle应该是因为回调不应该在 aftersettle返回之前运行。(ES2015 的 Promise 做到了这两件事。jQueryDeferred没有。)

  2. then并且settle应该确保回调中的失败(例如异常)不会直接传播到调用thensettle. 这与上面的#1 部分相关,与下面的#3 更相关。

  3. then应该根据调用回调的结果返回一个新的承诺(然后,或以后)。这对于组合 promise-ified 操作是相当基础的,但会使上述内容明显复杂化。任何合理的承诺实现都可以。

  4. 我们需要不同类型的“解决”操作:“解决”(底层操作成功)和“拒绝”(失败)。一些用例可能有更多的状态,但解决和拒绝是基本的两个。(ES2015 的 promise 有 resolve 和 reject。)

  5. 我们可能会以某种方式将settle(或单独的resolveand reject)设为私有,这样只有 Promise 的创建者才能解决它。(ES2015 承诺 - 以及其他几个承诺 - 通过让Promise构造函数接受一个接收resolvereject作为参数值的回调来做到这一点,因此只有该回调中的代码可以解析或拒绝[除非回调中的代码以某种方式将它们公开]。)

等等等等。

于 2013-03-27T19:55:44.247 回答
15

有人可以用几行代码实现最基本的承诺吗?

这里是:

function Promise(exec) {
    // takes a function as an argument that gets the fullfiller
    var callbacks = [], result;
    exec(function fulfill() {
        if (result) return;
        result = arguments;
        for (let c;c=callbacks.shift();)
            c.apply(null, arguments);
    });
    this.addCallback = function(c) {
        if (result)
            c.apply(null, result)
        else
            callbacks.push(c);
    }
}

附加then链接(您需要答案):

Promise.prototype.then = function(fn) {
    return new Promise(fulfill => {
        this.addCallback((...args) => {
            const result = fn(...args);
            if (result instanceof Promise)
                result.addCallback(fulfill);
            else
                fulfill(result);
        });
    });
};

这两个片段有什么关系?

ajaxgetPromiseForAjaxResult函数调用:

function getPromiseForAjaxResult(ressource) {
    return new Promise(function(callback) {
        ajax({url:ressource}, callback);
    });
}
于 2013-03-27T20:04:13.043 回答
1

我已经在 ES7 中实现了一个。使用链接,它是 70 行,如果那算得少的话。我认为状态机是实现承诺的正确范例。生成的代码比许多if恕我直言更容易理解。在这篇文章中有充分的描述。

这是代码:

const states = {
    pending: 'Pending',
    resolved: 'Resolved',
    rejected: 'Rejected'
};

class Nancy {
    constructor(executor) {
        const tryCall = callback => Nancy.try(() => callback(this.value));
        const laterCalls = [];
        const callLater = getMember => callback => new Nancy(resolve => laterCalls.push(() => resolve(getMember()(callback))));
        const members = {
            [states.resolved]: {
                state: states.resolved,
                then: tryCall,
                catch: _ => this
            },
            [states.rejected]: {
                state: states.rejected,
                then: _ => this,
                catch: tryCall
            },
            [states.pending]: {
                state: states.pending,
                then: callLater(() => this.then),
                catch: callLater(() => this.catch)
            }
        };
        const changeState = state => Object.assign(this, members[state]);
        const apply = (value, state) => {
            if (this.state === states.pending) {
                this.value = value;
                changeState(state);
                for (const laterCall of laterCalls) {
                    laterCall();
                }
            }
        };

        const getCallback = state => value => {
            if (value instanceof Nancy && state === states.resolved) {
                value.then(value => apply(value, states.resolved));
                value.catch(value => apply(value, states.rejected));
            } else {
                apply(value, state);
            }
        };

        const resolve = getCallback(states.resolved);
        const reject = getCallback(states.rejected);
        changeState(states.pending);
        try {
            executor(resolve, reject);
        } catch (error) {
            reject(error);
        }
    }

    static resolve(value) {
        return new Nancy(resolve => resolve(value));
    }

    static reject(value) {
        return new Nancy((_, reject) => reject(value));
    }

    static try(callback) {
        return new Nancy(resolve => resolve(callback()));
    }
}
于 2019-02-27T23:52:52.137 回答
0

这是一个轻量级的 Promise 实现,称为“序列”,我在日常工作中使用它:

(function() {
    sequence = (function() {
        var chained = [];
        var value;
        var error;

        var chain = function(func) {
            chained.push(func);
            return this;
        };

        var execute = function(index) {
            var callback;
            index = typeof index === "number" ? index : 0;

            if ( index >= chained.length ) {
                chained = [];
                return true;
            }

            callback = chained[index];

            callback({
                resolve: function(_value) {
                    value = _value;
                    execute(++index);
                },
                reject: function(_error) {
                    error = _error;
                    execute(++index);
                },
                response: {
                    value: value,
                    error: error
                }
            });
        };

        return {
            chain: chain,
            execute: execute
        };
    })();
})();

初始化后,您可以按以下方式使用序列:

sequence()
    .chain(function(seq) {
        setTimeout(function() {
            console.log("func A");
            seq.resolve();
        }, 2000);
    })
    .chain(function(seq) {
        setTimeout(function() {
            console.log("func B");
        }, 1000)
    })
    .execute()

要启用实际的链接,您需要调用 seq 对象的 resolve() 函数,您的回调必须将其用作参数。

Sequence 公开了两个公共方法:

  • 链 - 此方法只是将您的回调推送到私有数组
  • 执行 - 此方法使用递归来启用回调的正确顺序执行。它基本上按照您通过将 seq 对象传递给每个回调的顺序来执行您的回调。一旦当前回调被解决/拒绝,就会执行下一个回调。

“执行”方法是魔法发生的地方。它将“seq”对象传递给所有回调。因此,当您调用 seq.resolve() 或 seq.reject() 时,您实际上会调用下一个链式回调。

请注意,此实现仅存储来自先前执行的回调的响应。

更多示例和文档,请参考: https ://github.com/nevendyulgerov/sequence

于 2017-06-25T16:38:49.067 回答
0

这是一个对我有用的简单 Promise 实现。

    function Promise(callback) {
        this._pending = [];
        this.PENDING = "pending";
        this.RESOLVED = "resolved";
        this.REJECTED = "rejected";
        this.PromiseState = this.PENDING;
        this._catch = function (error) {
            console.error(error);
        };
        setTimeout(function () {
            try {
                callback.call(this, this.resolve.bind(this), this.reject.bind(this));
            } catch (error) {
                this.reject(error);
            }
        }.bind(this), 0)
    };
    Promise.prototype.resolve = function (object) {
        if (this.PromiseState !== this.PENDING) return;
        while (this._pending.length > 0) {
            var callbacks = this._pending.shift();
            try {
                var resolve = callbacks.resolve;
                if (resolve instanceof Promise) {
                    resolve._pending = resolve._pending.concat(this._pending);
                    resolve._catch = this._catch;
                    resolve.resolve(object);
                    return resolve;
                }
                object = resolve.call(this, object);
                if (object instanceof Promise) {
                    object._pending = object._pending.concat(this._pending);
                    object._catch = this._catch;
                    return object;
                }
            } catch (error) {
                (callbacks.reject || this._catch).call(this, error);
                return;
            }
        }
        this.PromiseState = this.RESOLVED;
        return object;
    };
    Promise.prototype.reject = function (error) {
        if (this.PromiseState !== this.PENDING) return;
        this.PromiseState = this.REJECTED;
        try {
            this._catch(error);
        } catch (e) {
            console.error(error, e);
        }
    };
    Promise.prototype.then = function (onFulfilled, onRejected) {
        onFulfilled = onFulfilled || function (result) {
            return result;
        };
        this._catch = onRejected || this._catch;
        this._pending.push({resolve: onFulfilled, reject: onRejected});
        return this;
    };
    Promise.prototype.catch = function (onRejected) {
        // var onFulfilled = function (result) {
        //     return result;
        // };
        this._catch = onRejected || this._catch;
        // this._pending.push({resolve: onFulfilled, reject: onRejected});
        return this;
    };
    Promise.all = function (array) {
        return new Promise(function () {
            var self = this;
            var counter = 0;
            var finishResult = [];

            function success(item, index) {
                counter++;
                finishResult[index] = item;
                if (counter >= array.length) {
                    self.resolve(finishResult);
                }
            }
            for(var i in array) {
                var item = array[i];
                if (item instanceof Promise) {
                    item.then(function (result) {
                        success(result,this);
                    }.bind(i), function (error) {
                        array.map(function (item) {
                            item.PromiseState = Promise.REJECTED
                        });
                        self._catch(error);
                    })
                } else {
                    success(item, i);
                }
            }
        });
    };
    Promise.race = function (array) {
        return new Promise(function () {
            var self = this;
            var counter = 0;
            var finishResult = [];
            array.map(function (item) {
                if (item instanceof Promise) {
                    item.then(function (result) {
                        array.map(function (item) {
                            item.PromiseState = Promise.REJECTED
                        });
                        self.resolve(result);
                    }, function (error) {
                        array.map(function (item) {
                            item.PromiseState = Promise.REJECTED
                        });
                        self._catch(error);
                    })
                } else {
                    array.map(function (item) {
                        item.PromiseState = Promise.REJECTED
                    });
                    self.resolve(item);
                }
            })
        });
    };
    Promise.resolve = function (value) {
        return new Promise(function (resolve, reject) {
            try {
                resolve(value);
            } catch (error) {
                reject(error);
            }
        });
    };
    Promise.reject = function (error) {
        return new Promise(function (resolve, reject) {
            reject(error);
        });
    }

在这里讨论。小提琴:在这里

于 2018-06-15T14:53:40.347 回答
-1

这是承诺架构的绝对最小值

function Promise(F) {
  var gotoNext = false;
  var stack = [];
  var args = [];

  var isFunction = function(f) {
    return f && {}.toString.call(f) === '[object Function]';
  };

  var getArguments = function(self, _args) {
    var SLICE = Array.prototype.slice;

    _args = SLICE.call(_args);
    _args.push(self);

    return _args;
  };

  var callNext = function() {
    var method = stack.shift();

    gotoNext = false;
    if (isFunction(method)) method.apply(null, args);
  };

  var resolve = [(function loop() {
    if (stack.length) setTimeout(loop, 0);
    if (gotoNext) callNext();
  })];

  this.return = function() {
    gotoNext = true;
    args = getArguments(this, arguments);
    if(resolve.length) resolve.shift()();

    return this;
  };

  this.then = function(fn) {
    if (isFunction(fn)) stack.push(fn);

    return this;
  };

  return this.then(F).return();
}


// --- below is a working implementation --- //

var bar = function(p) {
  setTimeout(function() {
    console.log("1");
    p.return(2);
  }, 1000);
};

var foo = function(num, p) {
  setTimeout(function() {
    console.log(num);
    p.return(++num);
  }, 1000);
};

new Promise(bar)
  .then(foo)
  .then(foo)
  .then(foo);

于 2018-11-18T10:49:28.650 回答