菜园前端
2021-09-18 16:21:40浏览 821
Promise 用法
let request = new Promise((resolve, reject) => {
// 表达式
if (true) {
resolve({ age: 20 });
} else {
reject('请求接口失败');
}
});
request
.then(res => {
console.log('res', res); // { age: 20 }
})
.catch(res => {
console.log('res2', res); // 请求接口失败
});
Promise.all 用法
let requestA = new Promise(resolve => {
setTimeout(() => {
resolve({ requestA: 20 });
}, 1000 * 2);
});
let requestB = new Promise(resolve => {
resolve({ requestB: 50 });
});
let requestAll = Promise.all([requestA, requestB]).then(res => {
console.log('res', res); // [{ requestA: 20 }, { requestB: 50 }]
});