Promise和async/await都是异步处理的方法。async/await看起来更简单易用。
Promise:构造函数
- resolve 成功回调,p.then(res => { console.log(res)})获取回调成功数据。
- reject 失败回调, p.catch(res => { console.log(res)})获取回调失败数据。
let p = new Promise(function(resolve,reject){
resolve('success');//成功回调
reject('error');//失败回调
})
//获取回调成功的数据
p.then(res => {
console.log(res);
});
//获取回调失败的数据
p.catch(res => {
console.log(res);
})
Promise.resolve() 和 Promise.reject()
-
Promise.resolve(p)
和p.then(res => {console.log(res)})
一样 -
Promise.reject(p)
和p.catch(res => {console.log(res)})
一样
let pp = Promise.resolve(p);
p.then(res => {
console.log(res);
});
let pp = Promise.reject(p);
p.catch(res => {
console.log(res);
});
多个函数Promise.all()
let p1 = Promise.resolve(123);
let p2 = Promise.resolve('hello');
let p3 = Promise.resolve('success');
Promise.all([p1,p2,p3]).then(result => {
console.log(result);
}).catch(result => {
console.log(result);
});
多个函数Promise.race():捕捉返回快的
function sleep(time) {
return new Promise((resolve,reject) => {
setTimeout(() => {
res(time);
},time);
});
}
let p1 = sleep(500);
let p0 = sleep(2000);
Promise.race([p1,p0]).then(result => {
console.log(result);//p1的结果
});
let p2 = new Promise((resolve,reject) => {
setTimeout(()=>{
reject('error');
},1000);
});
Promise.race([p0,p2]).then(result => {
console.log(result);//p2的结果
}).catch(result => {
console.log(result);
});
Async-Await :其实就是语法糖
对比 promise ,Async-Await 用法极其简单。
async function p() {
let result = await Promise.resolve(123);//直接使用回调
console.log(result);
return result;
}
p()//获取回调数据
//请求数据
//直接处理promise返回
async function pp(){
let data = await axios("xxx").then(res => res.data);
return data
}
//返回promise再处理
async function pp(){
let data = await axios("xxx");
return data
}
pp().then(res => res.data)
pp().catch(err => console.log(err))//错误处理
try catch捕捉错误时,内部错误不会被捕捉,还是需要catch回调捕捉。
let p = new Promise((resolve,reject) => {
setTimeout(() => {
reject('error');
},1000);
});
async function demo(params) {
try {
let result = await p;
}catch(e) {
console.log(e);
}
}
demo();
网友评论