promise specification

Article Directory

promise was first put forward in commonjs community, it was made a lot of specification. Comparative accepted that promise / A specification. Later, people on this basis. It proposes promise / A + specification, which is the actual implementation of the industry norm. es6 this specification is employed.

promise / A specification here

promise / A + specification in here there are Chinese version

However, the specification of this thing looked more obscure. Here to talk about the specific usage of promise.

Defined in the specification

What is the promise of it, it means a promise, I promise you told me to do what I will do in the future, but I do have to wait for the time.

A promise object has three states, ready state (Pending), successful state (Fulfilled), a failure state (rejected).

We look promise object constructor:

1
2
3
4
5
6
7
8
9
10
11
var promise = new Promise(function(resolve, reject) {
    
        // reject (new Error ( 'promise some errors ..')) 
    //}

    // an asynchronous operation, such as ajax request 
    the setTimeout ( function () { 
        Resolve ( 'asynchronous request into the end of a complete state ..' )
    },1000)

});

The initial state of the object is generally promise ready state, and the state can only be converted promise object state or ready state to a ready state to a successful failure state.

  • resolve will promise into successful state.
  • will reject promise into failure state.

The method then promise object

We can then use the object's methods promise to add this object inside the callback function. Call for:

1
promise.then(onFulfilled, onRejected)

then accepts a success callback, and failed callback. They are optional parameters.
When the object is in standby promise of these functions is not performed immediately. But wait.
When the promise object becomes a successful state calls onFulfilled, the value of the parameter passed resolve.
Failure state will be called into onRejected, the parameter value passed reject.

Since then a promise to return the object. So support for chained calls:

1
promise.then(onFulfilled, onRejected).then(onFulfilled, onRejected)

then in charge of the object to promise to add functions much as you want to add.

  • If the object is in standby promise to wait. Until the state began to change execution.
  • If the promise is already at the end of the object state (success or failure) then add the callback and then directly call the corresponding callback.
  • Also before the return value of a function onFulfilled if not promise. As will be parameters of a onFulfilled. onRejected similar.

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// onRejected null may be omitted 
promise.then ( function (prevValue) {

    the console.log ( 'Resolve values:' + prevValue)

    return  "I was the second argument passed to the callback" 
}, null ) .then ( function (value) { 
    the console.log ( 'Report:' + value)
    console.log ( 'I was the last one' )
})

/*
*result
Resolve the value: asynchronous request end. . It becomes a complete state
Report: I was the second parameter passed to the callback
I was the last one
*/

Wait until you can see the front of the asynchronous operation is over, will be behind the implementation.

In addition, if onFulfilled a new promise to return the object, then added that after the operation functions will be hosting a new promise to the object. Then execute the function after the operation is not performed by the final say on the subject of new promise.

such as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
promise.then(function(prevValue){

    the console.log ( 'Resolve values:' + prevValue)

    var newPromise =   new new Promise ( function (Resolve, Reject) { 
         the setTimeout ( function () { 
            Resolve ( 'after 2 seconds, a new promise becomes a complete state' )
         },2000)

    })
    // returns the new Promise 
    console.log ( 'returns a promise, began hosting.' )
     Return newPromise

},null).then(function(value){
    console.log('报告:'+ value)
    console.log ( 'I was the last one' )
})
/*
*result
resolve the value: asynchronous request end. . End becomes large column   promise specification to state
Returns a promise, began hosting.
Report: 2 seconds after the completion of a new state into promise
I was the last one
*/

The method object catch promise

Previous methods used to capture then come inside reject the error, it means a special then

1
2
3
4
5
6
7
8
9
promise.catch ( function (error) { 
  the console.log ( 'Error!' , error);
});

//Equivalent to

promise.then ( null , function (error) { 
  the console.log ( 'Error!' , error);
});

Class and reject method resolve Promise

Promise.resolve
accepted parameters if the object is a promise to return directly.
If it is a non-promise, but the object has a method will then try to convert into a state of promise success objects.
If the values do not have a method would then passed to the next onFulfilled function, and generates a promise in successful state of the object.

Promise.reject
accepted parameters if the object is a promise to return directly.
If it is a non-promise, but the object having the method then attempts promise selected objects into a failed state.
If the values do not have a method would then passed to the next onRejected function. And generating a promise objects in a failed state.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var a = Promise.resolve(true)
//same as
var a = new Promise(function(resolve,reject){
    //立即变成成功状态
    resolve(true)
})

var b = Promise.reject(true)
//same as
var b = new Promise(function(resolve,reject){
    //立即变成失败状态
    reject(true)
})


//使用Promise.resolve转换不标准的jQuery的promise对象
var promise = Promise.resolve($.get('http://www.taobao.com'));

Promise的类方法all和race

Promise.all用来包装一系列的promise对象返回一个包装后的promise对象,比如我们称之为A。

  • 当所有的promise对象都变成成功状态(fulfilled)后。这个包装后的A才会把自己变成成功态。A会等最慢的那个promise对象变成成功态(fulfilled)后把自己变成成功态。
  • 只要其中一个promise对象变成失败态(rejected),包装后的A就变成rejected,并且第一个rejected传递的值,会传递给A后面使用then添加的onRejected回调。
1
2
3
4
var a = new Promise(function(resolve,reject){})
var b = Promise.resolve(true)

Promise.all([a,b])

Promise.race也是用来包装一系列的promise对象返回一个包装后的promise对象,比如我们称之为B。跟all不同的是,只要有一个对象变成了成功状态(fulfilled),B就会变成成功状态。

1
Promise.race([a,b])

all是一种与的关系,而race是一种或的关系。

Promise的类方法defer使用

其实除了在构造函数里面使用resolve,reject去改变一个promise对象的状态外,我们还有另外一种方式。那就是defer。
例子:

1
2
3
4
5
6
7
8
9
10
promise.then(function(val){

    var d = Promise.defer()
    setTimeout(function(){
        d.resolve('2秒后,新的promise变成完成态')
        //d.reject('err')
    },2000)
    //返回自己的promise对象
    return d.promise
})

Promise.defer()生成一个defer对象。这个对象d具有一个promise对象属性。d.resolve会把管理的promise变成完成态,同理d.reject会将管理的promise变成失败态。

整个promise的用法就说完了。

其实A+规范中只定义了then函数的具体细节,而promise状态的改变都是前人的经验慢慢积累后总结出的一套使用方式

参考链接:

  1. http://www.w3ctech.com/topic/721
  2. http://www.cnblogs.com/fsjohnhuang/p/4135149.html
  3. http://wohugb.gitbooks.io/ecmascript-6/content/docs/promise.html

Guess you like

Origin www.cnblogs.com/wangziqiang123/p/11711234.html