Promise,前端绕不过去的坎,请说说你对promise的理解,请实现一个简单的promise,类似问题比比皆是,今天给大家捋捋
var promise = new Promise(function(resolve, reject) {
if (...) { // succeed
resolve(result);
} else { // fails
reject(Error(errMessage));
}
});
Promise 实例拥有 then ⽅法(具有 then ⽅法的对象,通常被称为 thenable )。 它的使⽤⽅法如下:
promise.then(onFulfilled, onRejected)
接收两个函数作为参数,⼀个在 fulfilled 的时候被调⽤,⼀个在 rejected 的时候被 调⽤,接收参数就是 future , onFulfilled 对应 resolve , onRejected 对应reject
接下来加上catch,看看下面这个例子
new Promise(resolve => {a(resolve);}).then(res =>{
const a1 = res;
console.log(a1);
new Promise((resolve, reject) => { b(resolve, reject);}).then(resolve => {
const b1 = resolve;
console.log(a1 + b1);
new Promise((resolve, reject) => { c(resolve, reject);}).then(resolve => {
const c1 = resolve;
console.log(a1+ b1 + c1);
}
// , reject => {
// const c2 = reject;
// console.log(c2)
// }
).catch(res => {
console.log(res);
});
}).catch(res =>{
console.log(res);
})
});
function a(resolve) {
setTimeout(() => { resolve(3)},3000)
}
function b(resolve, reject) {
setTimeout(() => {
resolve(30)
// reject(30)
}, 3000)
}
function c(resolve, reject) {
let c1 = 5, c2 = 6;
setTimeout(() =>{ reject('我错了')},3000)
}
控制台,间隔3s依次打印 3, 33, ‘我错了’
catch 方法可以捕获到 catch 之前整条 promise 链路上所有抛出的异常
all 方法可以将多个Promise实例包装成一个新的Promise实例。同时,成功和失败的返回值是不同的,成功的时候返回的是一个结果数组,而失败的时候则返回最先被reject失败状态的值。
race 方法就是赛跑的意思,谁运行的快,就返回谁的结果,不管结果本身是成功状态还是失败状态。
具体代码如下:
let p1 = new Promise((resolve, reject) => {
setTimeout(() => { resolve(2)},3000);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(() => { resolve(20)}, 2000);
});
let p3 = new Promise((resolve, reject) => {
setTimeout(() => { reject('失败')}, 1000);
});
Promise.all([p1,p2]).then(result => {
console.log(result); // [2, 20]
}).catch(err =>{
console.log(err);
});
Promise.all([p1,p2,p3]).then(result => {
console.log(result);
}).catch(err => {
console.log(err); // 失败
});
Promise.race([p1,p2]).then(result => {
console.log(result); // 20
}).catch(err => {
console.log(err);
});
Promise.race([p1,p2,p3]).then(result => {
console.log(result);
}).catch(err => {
console.log(err); // 失败
});