es6语法中promise的使用方法
Promise是一个构造函数,它有resolve,reject,race等静态方法;它的原型(prototype)上有then,catch方法,因此只要作为Promise的实例,都可以共享并调用Promise.prototype上面的方法(then,catch)
Promise的使用语法:
new Promise(
function(resolve,reject){}
//或
(resolve, reject) => {} //es6箭头函数
);
在实例化Promise时需要传入一个函数方法作为参数,并且在Promise构造函数执行时同步执行。 //后面后称这个函数方法为fuc
var a = new Promise(function(resolve,reject){
var timeOut = setTimeout(function(){
console.log('执行操作1');
},1000);
});
1s后在控制台输出相应的结果,说明在实例化过程中,作为fuc也会执行。
函数还有两个参数resolve和reject,这两个参数也是函数方法,在fuc执行时被调用
首先我们来看看Promise的几种状态:
- pending: 初始状态,成功或失败状态。
- fulfilled: 意味着操作成功完成。
- rejected: 意味着操作失败。
当我们在fuc中调用resolve方法时,Promise的状态就变成fulfilled,即操作成功状态,当Promise状态为fullfilled状态时执行then方法里的操作,then方法里面有两个参数onfulfilled(Promise为fulfilled状态时执行) 和onrejected(Promise为rejected状态时执行),步骤如下:
实例化方法
resolve('这是数据1');
}, 1000);
});
用Promise的实例调用then方法
简单的理解就是调用resolve方法,Promise变为操作成功状态(fulfilled),执行then方法里面onfulfilled里的操作。其实then里面的函数就是我们平时所说的回调函数,只不过在这里只是把它分离出来而已
调用reject方法后,Promise状态变为rejected,即操作失败状态,此时执行then方法里面onrejected操作,上面我们提到了then方法有两个参数,一种是Promise状态为fulfilled时执行(onfullfilled),一种是Promise状态为rejected时执行(onrejected)
},function(reason){ //状态为rejected时执行
console.log(reason);
console.log('这是失败的操作');
});
catch方法
除了then方法外,Promise原型上还有另外一个叫catch的方法,catch方法其实跟then方法中的第二个参数一样,就是在Promise状态为rejected时执行,then方法捕捉到Promise的状态为rejected,就执行catch方法里面的操作
}).catch(function(reason){
console.log(reason);
console.log('这是失败的操作');
});
promise主要是为了解决js中多个异步回调难以维护和控制的问题.