ES6--Promise对象
Promise对象 (es6中是一个构造函数)
定义: 代表了某个未来才会知道的结果事件,并提供统一的接口
作用: 将异步操作以同步操作的流程表达出来,避免了层层嵌套的回掉函数
1.一个用promise对象实现的ajax操作
function getAjax(url, data) {
return new Promise((resolve, reject) => {
$.ajax({
url: url,
data: data,
dataType: 'json',
method: 'GET',
}).then(function(data) {
resolve(data);
}).fail(function(error) {
//resolve(data); if has this, catch no use
reject(error);
});
});
}
getAjax("fake/es6Promise.json","author=sunny").then(function(data){
console.log(data);
},function(error){
console.log(error);
});
//? 实例的状态应该这么去check? pending/fulfilled/rejected/resolved
2.Promise.prototype.then()
用法: 两个参数--接受两个回掉函数,第一个是Promise对象状态为resolve时的回掉函数第二个是Promise对象状态为rejected时的回掉函数
特点: 可以链式写法,第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数
getAjax("fake/es6Promise.json","author=sunny").then(function(data){
console.log(data);
//这个return要为第二个then返回参数
return data.author;
}).then(function(data){
console.log(data);
//Sunny
});
3.Promise.prototype.catch()
定义: 是Promise.prototype.then(null, rejection)的别名,用于指定发生错误时的回调函数。
//wrong url
getAjax("fake/es6Promise1.json","author=sunny").catch(function(error){
console.log(error);
});
//但是如果在catch中有了resolve("sss"),那么就catch不到了