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

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() {}
});
主站蜘蛛池模板: 遂平县| 顺义区| 子长县| 枝江市| 呈贡县| 江永县| 石狮市| 丰城市| 轮台县| 佛山市| 云和县| 青川县| 洮南市| 武宣县| 都安| 云浮市| 沿河| 巢湖市| 红安县| 观塘区| 六安市| 江津市| 永吉县| 寿宁县| 石城县| 利川市| 井研县| 博乐市| 呼图壁县| 沙坪坝区| 喜德县| 新丰县| 民丰县| 名山县| 盐池县| 深泽县| 绥棱县| 平昌县| 遵化市| 都匀市| 呈贡县|