1、all
所有的Promise对象均成功后才会执行all中的then回调,否则返回的是最先rejected状态的值。
const promise1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('promise1'); }, 1000); }) const promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve('promise2'); }, 2000); }) const promise3 = new Promise((resolve, reject) => { setTimeout(() => { reject('promise3'); }, 1000); }) // 进入then回调,打印all_then Promise.all([promise1, promise2]).then((values) => { console.log('all_then', values) }).catch(reason => { console.log('all_catch', reason) }) // 进入catch回调,打印all_catch Promise.all([promise1, promise2, promise3]).then((values) => { console.log('all_then', values) }).catch(reason => { console.log('all_catch', reason) })
2、allSettled
所有的Promise对象均出现结果(无论成功或失败)后才会执行allSettled中的then回调(只会进入then回调)。
const promise1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('promise1'); }, 1000); }) const promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve('promise2'); }, 2000); }) const promise3 = new Promise((resolve, reject) => { setTimeout(() => { reject('promise3'); }, 1000); }) // 进入then回调 Promise.allSettled([promise1, promise2, promise3]).then((values) => { console.log('allSettled_then', values) }).catch(reason => { console.log('allSettled_catch', reason) })
3、any
和all相反,所有的Promise对象均失败后才会执行any中的失败回调,否则当任意一个Promise对象成功就会直接进入then回调。
const promise1 = new Promise((resolve, reject) => { setTimeout(() => { reject('promise1'); }, 1000); }) const promise2 = new Promise((resolve, reject) => { setTimeout(() => { reject('promise2'); }, 2000); }) const promise3 = new Promise((resolve, reject) => { setTimeout(() => { reject('promise3'); }, 1000); }) // 全部reject才会进入then回调 Promise.any([promise1, promise2, promise3]).then((values) => { console.log('any_then', values) }).catch(reason => { console.log('any_catch', reason) })
4、race
顾名思义,谁跑得快就返回当前Promise状态的值
const promise1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('promise1'); }, 500); }) const promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve('promise2'); }, 2000); }) const promise3 = new Promise((resolve, reject) => { setTimeout(() => { reject('promise3'); }, 1000); }) // 进入then回调 Promise.race([promise1, promise2, promise3]).then((values) => { console.log('race_then', values) }).catch(reason => { console.log('race_catch', reason) }) // const promise1 = new Promise((resolve, reject) => { // setTimeout(() => { // resolve('promise1'); // }, 1500); // }) // 进入catch回调 Promise.race([promise1, promise2, promise3]).then((values) => { console.log('race_then', values) }).catch(reason => { console.log('race_catch', reason) })
标签:promise1,resolve,js,race,Promise,reject,catch,promise2 From: https://www.cnblogs.com/smile-fanyin/p/16659005.html