2021年7月1日 星期四

更新 Promise 的範例

 最近接觸到不少 Promise 操作,早期抄的一些範例也已經不合時宜不易讀,因此重寫一下理解。

創造一個 Promise 物件:

new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log("a"), resolve("a");
          }, Math.floor(Math.random() * 5* 1000);
        });

用 setTimeout 做出時間差,模擬真正 API 回來時間差的情境;

Promise 物件有三種狀態:pending(等待),fulfilled(已完成),rejected(已失敗);

Promise 物件有 resolve 與 reject 兩種回傳,resolve 是成功,reject 是失敗;

當串聯操作的時候,有幾種情況要考慮:需不需要照順序執行?需不需要依序得到結果?

先創造範例 a,b,c 三個 function

  const a = () => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log("a"), resolve("a");
          }, Math.floor(Math.random() * 5* 1000);
        });
      };
      const b = () => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log("b"), resolve("b");
          }, Math.floor(Math.random() * 5* 1000);
        });
      };
      const c = () => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log("c"), resolve("c");
          }, Math.floor(Math.random() * 5* 1000);
        });
      };

照順序執行:

console.log(a().then(b()).then(c()))

直接用 .then 或 .catch 可以按順序執行。不過 return 的順序則不一定。

依序得到結果:

  const enter = async () => {
        const cc = await c();
        const bb = await b();
        const aa = await a();
      };
      console.log("c->b->a"enter());

透過 ES6 async await ,使每個 Promise 得到結果才執行下一個,由於這樣一串時間會拖很長,務必將 function 與主要組件拆開,避免主要畫面轉圈圈轉不完。

整個都綁在一起不怕一個錯就全都跳錯,或是針對裡面的 Promise 物件錯誤有調整 resolve 的話,也可以用 Promise.all 來進行處理。

這個範例應該複製貼上都跑得了,也可以觀察 return 的順序,如有錯誤還請不吝指教。


沒有留言:

張貼留言