new Promise(
function (resolve, reject) {
resolve('hello') // 数据处理完成
reject('bye') // 数据处理出错
}
).then(
(res) => {console.log(res)}, // res == hello
(err) => {console.log(err)} // err == bye
)
new Promise(resolve => {
setTimeout(() => {
resolve('hello')
}, 2000)
}).then(res => {
console.log(res)
})
new Promise(resolve => {
setTimeout(() => {
resolve('hello')
}, 2000)
}).then(val => {
console.log(val) // val == 'hello'
return new Promise(resolve => {
setTimeout(() => {
resolve('world')
}, 2000)
})
}).then(val => {
console.log(val) // val == 'world'
})
let pro = new Promise(resolve => {
setTimeout(() => {
resolve('hello world')
}, 2000)
})
setTimeout(() => {
pro.then(value => {
console.log(value) // value == hello world
})
}, 2000)
小结:promise作为队列最为重要的特性,我们在任何一个地方生成了一个promise队列后我们可以把他作为一个变量传递到其他地方。
因为.then()返回的还是promise实例,所以会等里面的.then()执行完,在执行外面的。
var say = (str,time) =>{
return new Promise((resolve,reject) =>{
setTimeout(()=>{
console.log(str);
resolve(str);
},time)
})
}
say('你好',2000).then(res=>{
return say('我喜歡你',2000)
}).then(res=>{
return say('加个微信',2000)
}).then(res=>{
})
- //切菜
function cutUp(){
console.log('开始切菜。');
var p = new Promise(function(resolve, reject){ //做一些异步操作
setTimeout(function(){
console.log('切菜完毕!');
resolve('切好的菜');
}, 1000);
});
return p;
}
//烧水
function boil(){
console.log('开始烧水。');
var p = new Promise(function(resolve, reject){ //做一些异步操作
setTimeout(function(){
console.log('烧水完毕!');
resolve('烧好的水');
}, 1000);
});
return p;
}
Promise.all([cutUp(), boil()])
.then((result) => {
console.log('准备工作完毕');
console.log(result);
})
有一个promise最先完成就 reslove 返回哪个
下面以三张图片加载为例
//图片地址
var arr = [
"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/c0c05274f2fbb55fbccb89622f798907.jpg?w=632&h=340",
"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/b746a4db2e0473cc076a3a4b9bbe0235.jpg?w=632&h=340",
"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/816a66edef10673b4768128b41804cae.jpg?w=632&h=340"
]
//封装加载图片函数
var loadImg = url =>{
return new Promise((resolve, reject) => {
var img = document.createElement('img');
img.src = url;
img.width = 800;
img.onload = function() {
resolve(img);
}
img.onerror = function(event) {
reject(event);
}
})
}
Promise.race(arr.map(item => {
return loadImg(item);
})).then(res => {
document.body.append(res);
}).catch(err => {
console.error(err);
})
var say = (str,time,callback)=>{
setTimeout(()=>{
console.log(str);
if(callback){
callback();
}
},time)
}
say('你好',5000,()=>{
say('我喜欢你',3000,()=>{
say('加个微信',2000)
})
})
转换为Promise写法:
var say = (str,time) =>{
return new Promise((resolve,reject) =>{
setTimeout(()=>{
console.log(str);
resolve(str);
},time)
})
}
say('你好',2000).then(res=>{
return say('我喜歡你',2000)
}).then(res=>{
return say('加个微信',2000)
}).then(res=>{
})