promise,为了解决ajax嵌套引起的地狱回调,代码层层嵌套会很难懂
语法
var p1=new Promise(function(){
setTimeout(function(){
// resolve('成功了');//这里会走向成功,then
//reject('失败了');//这里会走向失败,catch
},1000)
})
p1.then(function(res){
console.log(res);
})
p1.catch(function(res){
console.log(res);
})
其实,ajax也可以做到扁平,但是需要给下一个ajax取名字,并且看着很绕。
有了promise,省去了取名字,看着还直观,缺点是每次还有new一个promise
下面举一个实战的例子
// 吃饭
new Promise(function(resolve, reject){
console.log('开始吃饭');
setTimeout(function(){
resolve();
// reject('饭吃了一半,去加班了');
},1000)
})
.then(function(){
return new Promise(function(resolve, reject){
console.log('吃饭完毕,开始刷碗');
setTimeout(function(){
resolve();
},1000)
})
})
.catch(function(res){
console.log(res);
})
.then(function(){
return new Promise(function(resolve, reject){
console.log('刷碗完毕,出去玩');
setTimeout(function(){
console.log('玩累了,回家吃饭');
},1000)
})
})