Promise
2020-01-17 本文已影响0人
BingeryLamb
Promise 用于封装异步操作,根据条件判断成功还是失败,条件自己定义(一般根据异步操作是否成功判断),以便进行后续的操作。
function getFloat (float){
return new Promise((resolve, reject)=>{
//异步操作
setTimeout(function(){
//自定义条件
if(float > 0.5){
resolve(float)
} else {
reject('error 数字少于0.5')
}
}, 800)
})
}
getFloat(Math.random()).then(function(float){
console.log(float)
return getFloat(Math.random())
}, function(error){
console.log(error)
}).then(function(float){
console.log(float)
return getFloat(Math.random())
}).then(function(float){
console.log(float)
})
// 4张图1,2,3,4
// 2在1后面画上
// 4在1,2,3后面画上
getImage('book1.png').then(function(img){
ctx.drawImage(img, 0, 0, 50, 50)
return Promise.all([getImage('book2.png'), getImage('book3.jpg')])
}).then(function(imgArr){
imgArr.forEach((img, index)=>{
ctx.drawImage(img, 60, 50 * index,50, 50)
})
return getImage('book4.png')
}).then(function(img){
ctx.drawImage(img, 120, 0, 50, 50);
})
Promise三个状态 pending fulfilled reject
Promise.resolve 产生一个新的Promise
Promise.resolve(value);
Promise.resolve(promise); // 拷贝
Promise.resolve(theanable);
theanable
var test = {
then: (resolve, reject)=>{
console.log(1);
resolve(2)
}
}
var promise = Promise.resolve(test) // 1
promise.then((data)=>{
console.log(data) // 2
})
值穿透
Promise.resolve('foo')
.then(Promise.resolve('bar'))
.then(function(result){
console.log(result)
})
// foo
//.then 或者 .catch 的参数期望是函数,传入非函数则会发生值穿透。