官术网_书友最值得收藏!

The states and return values of a promise

From Chapter 1, Promises.js, we are already aware that a promise is based on three states. Let's brush up our memory on these states, in accordance with promises paradigm.

Promise has three states:

  • Unfulfilled promise
  • Fulfilled promise
  • Failed promise

A promise exists within these three states.

The beginning of a promise is from an unfulfilled state. This is due to the fact that a promise is a proxy for an unknown value.

When the promise is filled with the value it's waiting for, it's in the fulfilled state. The promise will be labeled as failed if it returns an exception.

A promise may move from an unfulfilled to a fulfilled or failed state. Observers (or the objects/events waiting) are notified when the promise is either rejected or fulfilled. Once the promise is rejected or resolved, its output (value or state) cannot be modified.

The following code snippet will help you understand more easily than theory:

// Promise to be filled with future value
var futureValue = new Promise();

// .then() will return a new promise
var anotherFutureValue = futureValue.then();

// Promise state handlers (must be a function ).
// The returned value of the fulfilled / failed handler will be the value of the promise.
futureValue.then({

    // Called if/when the promise is fulfilled
    fulfilledHandler: function() {},

    // Called if/when the promise fails
    errorHandler: function() {},

    // Called for progress events (not all implementations of promises have this)
    progressHandler: function() {}
});
主站蜘蛛池模板: 工布江达县| 九寨沟县| 桦南县| 固安县| 肃宁县| 东方市| 运城市| 邵阳市| 呼图壁县| 建宁县| 鞍山市| 红安县| 大理市| 合作市| 鄂托克旗| 宝应县| 桐柏县| 新蔡县| 来凤县| 漳平市| 苍南县| 方城县| 沂水县| 修水县| 汨罗市| 乌鲁木齐县| 包头市| 乌兰县| 水富县| 黔江区| 尼玛县| 曲阜市| 珲春市| 兴安县| 苏尼特左旗| 庄河市| 金沙县| 奉贤区| 中宁县| 乌兰察布市| 恩施市|