简介
new Promise(function(resolve,reject){});
状态
- pending: 初始状态,成功或失败状态。
- fulfilled: 意味着操作成功完成。对应resolve
- rejected: 意味着操作失败。对应reject
resolve:使用resolve 状态变为fulfilled会调用第一个函数
var p = new Promise(function (resolve, reject) {
var timer = setTimeout(function () {
console.log('执行操作1');
resolve('这是数据1');
}, 1000);
});
p.then(function (data) {
console.log(data);
console.log('这是成功操作');
});
//执行操作1
//VM36:8 这是数据1
//VM36:9 这是成功操作
reject:使用reject 会调用第二个的then
var p = new Promise(function (resolve, reject) {
reject('这是数据2');
});
p.then(function(data){//状态为fulfilled时执行
console.log(data);
console.log('这是成功操作');
},function(reason){ //状态为rejected时执行
console.log(reason);
console.log('这是失败的操作');
});
//这是数据2
//VM42:10 这是失败的操作
catch:catch与reject一样
var p = new Promise(function (resolve, reject) {
reject('这是数据2');
});
p.then(function(data){
console.log(data);
console.log('这是成功操作');
}).catch(function(reason){
console.log(reason);
console.log('这是失败的操作');
});
//VM48:8 这是数据2
//VM48:9 这是失败的操作
目的:解决回调地狱
普通写法
setTimeout(function () {
console.log('我');
setTimeout(function () {
console.log('爱');
setTimeout(function () {
console.log('米');
setTimeout(function () {
console.log('饭');
}, 1000);
}, 1000);
}, 1000);
}, 1000);
//3
//VM54:2 我
//VM54:4 爱
//VM54:6 米
//VM54:8 饭
promise写法
function getStr1() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('我');
}, 1000);
});
}
function getStr2() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('爱');
}, 1000);
});
}
function getStr3() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('米');
}, 1000);
});
}
function getStr4() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('饭');
}, 1000);
});
}
getStr1().then(function (data) {
console.log(data);
return getStr2();
}).then(function (data) {
console.log(data);
return getStr3();
}).then(function (data) {
console.log(data);
return getStr4();
}).then(function (data) {
console.log(data);
})
//Promise {<pending>}
//VM59:30 我
//VM59:33 爱
//VM59:36 米
//VM59:39 饭