Promise入门
- 男女相爱了,女方向男方许下一个承诺怀孕
new Promise
,这是会产生两种结果怀上(resolve
)和没怀上(reject
),resolve
对应then
,reject
对应catch
,无论是否怀上都会执行finally
。
<script>
let isPregnant = false;
const promise = new Promise((resolve,reject)=>{
if(isPregnant){
resolve("孩子他爹");
}else{
resolve("老公")
}
})
promise
.then(name=>{
console.log(`男人成为了${name}`);
}).catch(name=>{
console.log(`男人成为了${name}`);
}).finally(()=>{
console.log("男人和女人最终结婚了");
})
</script>
- 下面是一个图片的异步加载过程,当图片加载成功时执行
resolve
方法,将图片渲染到页面,加载失败时reject
方法,输出加载错误。
<script>
let imgUrl = "https://ts1.cn.mm.bing.net/th/id/R-C.fd7cad22933db9caf2e02f2201cdacdb?rik=gJgWP1TDqA29CA&riu=http%3a%2f%2fimg.zcool.cn%2fcommunity%2f0109d25949e3baa8012193a3fb7c19.gif&ehk=pPVPiyQNUuMbzYgHC7KUMw7JBiep%2bDQKO82vNsJfX0o%3d&risl=&pid=ImgRaw&r=0";
const imgPromise = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => {
resolve(img);
}
img.onerror = () => {
reject(new Error("图片有误"));
}
})
}
imgPromise(imgUrl)
.then(img => {
document.body.appendChild(img);
})
.catch(err => {
document.body.innerHTML = err;
})
</script>
new Promise
但是未执行resolve、reject
,状态:pending
- 执行
resolve
状态:fullfilled
- 执行
reject
状态:rejected
const promise1 = new Promise((resolve,reject)=>{});
const promise2 = new Promise((resolve,reject)=>{resolve()});
const promise3 = new Promise((resolve,reject)=>{reject()});
console.log(promise1,`promise1`);
console.log(promise2,`promise2`);
console.log(promise3,`promise3`);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GHefBTrg-1678081565404)(D:/typoraImg/image-20230306115820468.png)]
不可变,resolve
和reject
谁先执行,promise的状态就是那个。
-
在then返回Promise实例,之后链式调用,来解决回调地狱。
function request1(){ return new Promise(resolve=>resolve(1)); } function request2(){ return new Promise(resolve=>resolve(2)); } function request3(){ return new Promise(resolve=>resolve(3)); } request1().then(v=>{ console.log(`第${v}层`); return request2(); }).then(v=>{ console.log(`第${v}层`); return request3(); }).then(v=>{ console.log(`第${v}层`); })
Promise.all([])
里面传入数组,会返回一个Promise实例,执行then方法时:- 如果都是
resolve
,那么会按照,传入参数的顺序输出。如下:虽然promise3是最先执行结束的,但是打印出来是[1,2,3]; - 如果有一个
reject
,那么立即执行reject
,其他的不会支持性,如果有多个reject
,只执行最先执行结束的。
- 如果都是
const promise1 = new Promise(resolve=>{
setTimeout(()=>{
resolve(1);
},3000)
})
const promise2 = new Promise(resolve=>{
setTimeout(()=>{
resolve(2);
},2000)
})
const promise3 = new Promise(resolve=>{
setTimeout(()=>{
resolve(3);
},1000)
})
const promiseAll = Promise.all([promise1,promise2,promise3]);
promiseAll.then(v=>{
console.log(v);
}).catch(v=>{
console.log('catch',v);
})
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6lKdGTDm-1678081565404)(D:/typoraImg/image-20230306131324825.png)]
Promise.race()
:谁先执行结束,就执行谁,然后不在执行其他Promise
,这里resolve
和reject
优先级相同。- Promise.all() 原理解析及使用指南 - 掘金 (juejin.cn)
- 关于 Promise.all 和 async await 这档子事儿 - 掘金 (juejin.cn)
const promise1 = new Promise(resolve=>{
setTimeout(()=>{
resolve(1);
},3000)
})
const promise2 = new Promise(resolve=>{
setTimeout(()=>{
resolve(2);
},2000)
})
const promise3 = new Promise(resolve=>{
setTimeout(()=>{
resolve(3);
},1000)
})
async function execute(){
await promise1.then(v=>console.log(v));
await promise2.then(v=>console.log(v));
await promise3.then(v=>console.log(v));
}
execute();