Promise状态:
pending:进行中
const promise = new Promise((resolve, reject) => {
})
console.log(promise);
// Promise { <pending> }
执行resolve变成成功fulfilled
const promise1 = new Promise((resolve, reject) => {
try {
let a = 5
resolve(a)
// Promise { 5 }
} catch (err) {
reject(err)
}
})
console.log(promise1);
执行reject变成失败rejected
Promise方法:
all()
只有Promise都成功才能执行all方法,如果Promise实例都变为Fulfilled状态,Promise.all返回的实例才会变成fulfilled状态并将Promise实例数组的所有返回值组成一个数组。
function p1() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('p1')
}, 2000)
})
}
function p2() {
return new Promise(function (resolve, reject) {
resolve('p2')
})
}
Promise.all(['a', 'b', p1(), p2()]).then((values) => {
console.log(values);
})
any()
与all相反,只要有一个Promise变为Fulfilled状态就能执行any方法。
race()
返回的Promise为先解决或拒绝的Promise值。
// 解决
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'hello1')
})
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 50, 'hello2')
})
Promise.race([promise1, promise2]).then((value) => {
console.log(value);
})
// hello2
// 拒绝
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'hello1')
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 50, 'hello2')
});
Promise.race([promise1, promise2]).then((values) => {
console.log(values);
})
// triggerUncaughtException(err, true /* fromPromise */);
reject()
Promise.reject()返回带有拒绝原因的Promise对象。
const err = Promise.reject('错误');
console.log(err);
// Promise { <rejected> '错误' }
resolve()
Promise.resolve()返回实例的状态为fullfilled。
const fullfilled = Promise.resolve('成功')
fullfilled.then((value) => {
console.log(value);
})
// 成功
then catch
then处理成功catch处理失败
const promise = new Promise(function (resolve, reject) {
setTimeout(function () {
try {
// throw new Error('错误')
let a = 10 /2
resolve(a)
} catch (err) {
reject(err)
}
}, 1000)
})
promise.then(function (val) {
console.log(val);
// 5
}).catch(function (err) {
console.log(err);
})