Promise 是异步编程的一种解决方案,解决——回调函数和事件
ES6 规定,Promise对象是一个构造函数,用来生成Promise实例。
下面代码创造了一个Promise实例。
基本用法
ES6 规定,Promise对象是一个构造函数,用来生成Promise实例。
1
2
3
4
|
const promise = new Promise( function (resolve, reject) { //resolve (data) 成功 //reject (error )失败 }); |
Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数。
1
2
3
4
5
|
promise.then( function (value) { // success }, function (error) { // err }); |
then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数。
下面是一个Promise对象的简单例子
1
2
3
4
5
6
7
8
|
function fun(ms){ return new promise((res,rej) => { setTimeout(res,ms) }) } fun(100).then((val) => { console.log(val) }) |
promise还可以用来加载图片
1
2
3
4
5
6
7
8
9
10
11
12
|
function loadImageAsync(url) { return new Promise( function (resolve, reject) { const image = new Image(); image.onload = function () { resolve(image); }; image.onerror = function () { reject( new Error( 'Could not load image at ' + url)); }; image.src = url; }); } |
上面代码中,使用Promise包装了一个图片加载的异步操作。如果加载成功,就调用resolve方法,否则就调用reject方法。
2,用Promise对象实现的 Ajax 操作的例子。
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
26
|
const getJSON = function (url) { const promise = new Promise( function (resolve, reject){ const handler = function () { if ( this .readyState !== 4) { return ; } if ( this .status === 200) { resolve( this .response); } else { reject( new Error( this .statusText)); } }; const client = new XMLHttpRequest(); client.open( "GET" , url); client.onreadystatechange = handler; client.responseType = "json" ; client.setRequestHeader( "Accept" , "application/json" ); client.send(); }); return promise; }; getJSON( "/posts.json" ).then( function (json) { console.log( 'Contents: ' + json); }, function (error) { console.error( '出错了' , error); }); |
注意,调用resolve或reject并不会终结 Promise 的参数函数的执行。
Promise.prototype.finally()
finally方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的。
1
2
3
4
|
promise .then(result => {···}) . catch (error => {···}) .finally(() => {···}); |
上面代码中,不管promise最后的状态,在执行完then或catch指定的回调函数以后,都会执行finally方法指定的回调函数,finally本质上是then方法的特例。
Promise.resolve()
1
2
|
//有时需要将现有对象转为 Promise 对象,Promise.resolve方法就起到这个作用。 const jsPromise = Promise.resolve($.ajax( '/whatever.json' )); |
上面代码将 jQuery 生成的deferred对象,转为一个新的 Promise 对象。
Promise.resolve等价于下面的写法。
1
2
3
4
|
Promise.resolve( 'foo' ) // 等价于 new Promise(resolve => resolve( 'foo' )) //Promise.resolve方法的参数分成四种情况。 |