通过promise实现多个异步操作的函数按照顺序执行,防止出现回调地狱;
//异步方法一
function getone(resolve,reject){
setTimeout(function(){
resolve("getone");
},3000)
}
//异步方法二
function gettwo(resolve,reject){
setTimeout(function(){
resolve("gettwo");
},3000)
}
//异步方法三
function getthree(resolve,reject){
setTimeout(function(){
resolve("getthree");
},3000)
}
var result = new Promise(getone)
.then(function(resultone){
console.log('----------one------------');
console.log(resultone);
return new Promise(gettwo);
})
.then(function(resulttwo){
console.log('----------two------------');
console.log(resulttwo);
return new Promise(getthree);
})
.then(function(resultthree){
console.log('-----------three---------');
console.log(resultthree);
})
.catch(function(err){
console.log(err);
})
以上getone
,gettwo
,getthree
就是平时需要的异步方法,比如ajax发起的请求;