Promise 用法
程序员文章站
2022-07-02 22:56:50
...
1.单个请求时
let p = new Promise((resolve,reject)=>{
setTimeout(function () {
if (true) {
resolve('xx')
} else {
reject('yy')
}
},100)
})
p.then()
.catch()
2.多个请求时(各个请求没有相关)
let p1 = new Promise((resolve,reject)=>{
setTimeout(()=>{resolve('p1')},1000)
});
let p2 = new Promise((resolve,reject)=>{
setTimeout(()=>{reject('p2')},2000)
});
Promise.all([p1,p2]).then(param=>{
console.log(param)
console.log('所有请求完成')
}).catch(err=>{
console.log(err)
})
3.有请求完成 race
let p1 = new Promise((resolve,reject)=>{
setTimeout(()=>{resolve('p1')},1000)
});
let p2 = new Promise((resolve,reject)=>{
setTimeout(()=>{reject('p2')},2000)
});
Promise.race([p1,p2]).then(param=>{
console.log(param)
console.log('有请求完成了')
}).catch(err=>{
console.log(err)
})
4.一个请求依赖另一个求情的结果时
async function fn() {
let a,a2;
let p = new Promise((resolve,reject) => {
a = '11';
resolve('11')
});
await p;
let p2 = new Promise((resolve,reject) => {
a2 = a + '22';
resolve('22')
});
await p2;
console.log(a2)
}
fn()
写的比较简陋,朋友们多多指教
上一篇: promise用法
下一篇: promise 用法