这篇文章要介绍一些常用的 Promise 的方法
首先我们先来看看这个範例
// 定义function promiseFn (num, timeout = 500) { return new Promise( (resolve, reject) => { setTimeout(() => { if (num) { resolve(`成功 ${num}`); } else { reject('失败'); } }, timeout); });}// 执行promiseFn(1, 2000) .then((res) => { console.log(res); }, (rej) => { console.log(rej); });
执行了以后过了两秒才出现结果,符合我们的设计预期!
这边我们把 timeout 的时间改为参数传入,并且有给予他预设值。
如果我现在要同时发出不同的非同步行为那该怎么办?
上一个篇文章,我们介绍到链接的方法,等前一个完成之后在执行另一个,那么如果现在我要同时送出多个非同步的行为的话,就要使用到 Promise.all 的方法!
Promise.all([ promiseFn(1, 2000), promiseFn(2, 500), promiseFn(3, 5000)]) .then((res) => { console.log(res); });
使用的方法就是传入一个阵列,包含你要同时发出请求的 Promise 执行函式。
之后等所有的非同步行为都得到结果以后,就会回传结果的阵列!
这个就是 Promise.all
的基本使用方法,特别要注意的是,如果其中的任一个非同步行为是reject 的状态的话,就会直接进到 catch 的状态!
// 执行promiseFn(1, 2000) .then((res) => { console.log(res); }, (rej) => { console.log(rej); });Promise.all([ promiseFn(1, 2000), promiseFn(0, 500), promiseFn(3, 5000)]) .then((res) => { console.log(res); }) .catch((rej) => { console.log(rej); });
另外一个比较常用的方法就是 Promise.race()
,基本上,跟 Promise.all()
的使用方法一样,但他只会回传第一个完成的结果,不论是成功或是失败。
Promise.race([ promiseFn(0, 2000), promiseFn(2, 500), promiseFn(3, 5000)]) .then((res) => { console.log(res); }) .catch((rej) => { console.log(rej); });
以上就是我们在使用 Promise 的时候,比较常使用到的两个方法 .all 以及 .race, 如果没有问题的话我们就可以往下一篇文章继续学习噜!汪汪~