Promise的全部用法 #148
Anuluca Date : 2024-08-14 Tags : 2
1.单独使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| const promiseFunc = (param) => { return new Promise((resolve, reject) => { if (param) { setTimeout(() => { resolve({ code: "200", data: { param, message: "成功", }, }); }, 1000); } else { setTimeout(() => { reject({ code: "400", data: { param, message: "失败", }, }); }, 1000); } }); };
getData(1) .then((res) => { console.log("res", res); }) .catch((err) => { console.log("err", err); }) .finally(() => { console.log("我是 finally 总是最后执行"); });
|
2.Promise.all
Promise.all([promise1,promise2,promise3])
promise1、promise2、promise3全部执行完毕,有一个报错回调则执行reject
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const promise1 = new Promise((resolve, reject) => { console.log("promise1"); setTimeout(() => { resolve("promise1:成功"); }, 1000); });
const promise2 = new Promise((resolve, reject) => { console.log("promise2"); setTimeout(() => { resolve("promise2:成功"); }, 1000); });
const promise3 = new Promise((resolve, reject) => { console.log("promise3"); setTimeout(() => { resolve("promise3:成功"); }, 1000); });
Promise.all([promise1, promise2, promise3]) .then((res) => { console.log("res", res); }) .catch((err) => { console.log("err", err); });
|
3.Promise.allSettled
Promise.allSettled([promise1,promise2,promise3])
promise1、promise2、promise3全部执行完毕,即使有报错也永远会执行then回调
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const promise1 = new Promise((resolve, reject) => { console.log("promise1"); setTimeout(() => { resolve("promise1:成功"); }, 1000); });
const promise2 = new Promise((resolve, reject) => { console.log("promise2"); setTimeout(() => { resolve("promise2:成功"); }, 1000); });
const promise3 = new Promise((resolve, reject) => { console.log("promise3"); setTimeout(() => { reject("promise3:失败"); }, 1000); });
Promise.allSettled([promise1, promise2, promise3]) .then((res) => { console.log("res", res); }) .catch((err) => { console.log("err", err); });
|
4.Promise.race
Promise.race([promise1,promise2,promise3])
promice、promise2、promise3谁最快执行完就进入回调
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const promise1 = new Promise((resolve, reject) => { console.log("promise1"); setTimeout(() => { resolve("promise1:成功"); }, 1000); });
const promise2 = new Promise((resolve, reject) => { console.log("promise2"); setTimeout(() => { resolve("promise2:成功"); }, 2000); });
const promise3 = new Promise((resolve, reject) => { console.log("promise3"); setTimeout(() => { reject("promise3:失败"); }, 3000); });
Promise.race([promise1, promise2, promise3]) .then((res) => { console.log("res", res); }) .catch((err) => { console.log("err", err); });
|