Promise解决异步回调的问题
{
//基本定义
let ajax=function(callback){
console.log("执行")
setTimeout(function(){
callback&&callback.call();
},1000)
};
ajax(function(){
console.log("执行完了")
})
//执行
//执行完了
}
{
let ajax=function(){
console.log("执行");
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve();
},1000)
})
}
ajax().then(function(){
console.log("执行完了")
})
//执行
//执行完了
}
{
let ajax=function(){
console.log("执行");
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve();
},1000)
})
}
ajax().then(function(){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve();
},2000)
})
}).then(function(){
console.log("执行完了")
})
//执行
//执行完了
}
{
let ajax=function(num){
console.log("执行");
return new Promise(function(resolve,reject){
if(num>5){
resolve()
}else {
throw new Error("出错了")
}
})
}
ajax(6).then(function(){
console.log(6)
}).catch(function(err){
console.log(err)
})
//6
ajax(4).then(function(){
console.log(6)
}).catch(function(err){
console.log(err)
})
//Error: 出错了
}
Promise.all和Promise.race
{
//所有图片加载完再加载页面
function loadImg(src) {
return new Promise((resolve,reject)=>{
let img=document.createElement('img');
img.src=src;
img.onload=function(){
resolve(img);
}
img.onerror=function(err){
reject(err);
}
})
}
function showImgs(imgs){
imgs.forEach(function(img){
document.body.appendChild(img)
})
}
Promise.all([
loadImg('http://img2.imgtn.bdimg.com/it/u=4155809725,2453290283&fm=27&gp=0.jpg'),
loadImg('http://img2.niutuku.com/desk/1208/1446/ntk-1446-13755.jpg'),
loadImg('http://img0.imgtn.bdimg.com/it/u=4273540577,2947670665&fm=214&gp=0.jpg')
]).then(showImgs)
}
{
//一个图片加载完就好
function loadImg(src) {
return new Promise((resolve,reject)=>{
let img=document.createElement('img');
img.src=src;
img.onload=function(){
resolve(img);
}
img.onerror=function(err){
reject(err);
}
})
}
function showImgs(img){
document.body.appendChild(img)
}
Promise.race([
loadImg('http://img2.imgtn.bdimg.com/it/u=4155809725,2453290283&fm=27&gp=0.jpg'),
loadImg('http://img2.niutuku.com/desk/1208/1446/ntk-1446-13755.jpg'),
loadImg('http://img0.imgtn.bdimg.com/it/u=4273540577,2947670665&fm=214&gp=0.jpg')
]).then(showImgs)
}
网友评论