promise与async、await
promise用法
- promise基本用法
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('p1-ok');
}, 1000);
});
let p2 = Promise.resolve('p2-ok');
p1.then((res) => {
console.log(res);// p1-ok
return p2;
}).then((res) => {
console.log(res);// p2-ok
// ...
});
-
Promise.all(Array[Promise] array, Function callback)
只有当数组里所有的promise实例执行成功,才会变为成功状态,成功回调函数的参数是所有传入的promise的返回值组成的数组
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('p1-ok');
}, 1000);
});
let p2 = Promise.resolve('p2-ok');
let p3 = Promise.reject(new Error('出错了!'));
let pAll = Promise.all([p1, p2, p3]);
pAll.then(res => {
console.log('全部执行成功', res);
}).catch(err => {
console.log('报错:' + err.message);// 报错:出错了!
}).finally(() => {
console.log('Promise.all执行完毕');// Promise.all执行完毕
});
-
Promise.race(Array[Promise] array, Function callback)
只要数组中有一个成功,就整个执行成功,成功回调函数的参数为最先执行成功的promise实例的返回值
// ...
let pRace = Promise.race([p1, p2, p3]);
pRace.then(res => {
console.log('至少一个执行成功', res);// 至少一个执行成功 p2-ok
});
async、await
async、await是generator函数的语法糖,是解决回调地狱的最新语法
async function demo() {
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('p1-ok');
}, 1000);
});
let p2 = Promise.resolve('p2-ok');
let p3 = Promise.reject(new Error('出错了!'));
try {
let resAll = await Promise.all([p1, p2, p3]);
console.log('resAll', resAll);
} catch(err) {
console.log('err', err.message);
}
let res = await Promise.race([p1, p2, p3]);
console.log('race', res);
}
demo();