javascript 的同步,異步; Promise 或 async await - daniel-qa/Vue GitHub Wiki

javascript 的同步,異步; Promise 或 async/await

Promise

  • 簡單範例:使用 Promise 和 .then() 處理異步操作

這裡是一個完整的範例,展示如何使用 Promise 和 .then() 來處理一個異步操作:

function asyncOperation() {
  return new Promise((resolve, reject) => {
    let success = true;  // 假設操作成功
    setTimeout(() => {
      if (success) {
        resolve("操作成功!");
      } else {
        reject("操作失敗!");
      }
    }, 2000);  // 模擬異步操作
  });
}

asyncOperation()
  .then((result) => {
    console.log(result);  // 如果操作成功,會顯示 "操作成功!"
  })
  .catch((error) => {
    console.log(error);   // 如果操作失敗,會顯示 "操作失敗!"
  });

Promise 是處理異步操作的基本工具,它能夠表示操作的成功、失敗以及其結果。

.then() 是用來處理成功結果的回調方法,可以鏈式調用以處理多個異步操作。

.catch() 用來捕獲錯誤,並在錯誤發生時執行相應的處理。


Promise 順序

console.log("開始");

new Promise((resolve, reject) => {
  console.log("執行中...");
  
  // 模擬成功
  resolve("成功結果");
  
  // 如果要模擬失敗就改成這行:
  // reject("錯誤發生");
})
.then(result => {
  console.log("成功:", result);
})
.catch(error => {
  console.log("失敗:", error);
});

console.log("結束");

輸出順序:

開始            // (1) 最先執行
執行中...       // (2) Promise 直接執行
結束            // (3) 同步代碼繼續執行
成功: 成功結果   // (4) .then() 等 Promise 完成後才執行

🎯 記住

Promise 是 非同步,但它建立時會立刻執行內容。

.then() 會等 resolve() 完成後執行。

.catch() 只會在 reject() 時執行。

如果沒有錯誤,.catch() 根本不會跑到。


  • 使用 then() 處理成功和錯誤
const promise = new Promise((resolve, reject) => {
  const success = true; // 假設這是成功的操作
  if (success) {
    resolve("操作成功");
  } else {
    reject("操作失敗");
  }
});

promise
  .then(
    (result) => { console.log("成功:" + result); },  // 當 Promise 成功時,執行這裡的程式碼
    (error) => { console.log("失敗:" + error); }    // 當 Promise 失敗時,執行這裡的程式碼
  );
  • 連鎖 Promise:.then() 可以鏈式調用

.then() 方法會返回一個新的 Promise,因此可以進行鏈式調用。這樣你可以連續處理多個異步操作。

const promise = new Promise((resolve, reject) => {
  resolve(10);  // 初始的值
});

promise
  .then((result) => {
    console.log(result); // 輸出 10
    return result * 2;  // 返回新的值 20
  })
  .then((result) => {
    console.log(result); // 輸出 20
    return result + 5;  // 返回新的值 25
  })
  .then((result) => {
    console.log(result); // 輸出 25
  });

第一個 .then() 處理結果,並返回 result * 2,第二個 .then() 接收並處理這個返回值。

  • 錯誤處理:.catch()

    Promise 也可以用 .catch() 來捕獲錯誤並處理。.catch() 用來捕捉鏈式 .then() 中的錯誤。

const promise = new Promise((resolve, reject) => {
  reject("出錯了!");
});

promise
  .then((result) => {
    console.log(result); // 不會執行
  })
  .catch((error) => {
    console.log(error);  // 輸出 "出錯了!"
  });

Promise 和 .then() 是 JavaScript 中用來處理異步操作的常見方式

Promise 是一個表示異步操作最終完成(或失敗)並返回結果的對象。.then() 是 Promise 的一個方法,用來處理成功結果或錯誤。

1. Promise 是什麼?

Promise 代表一個異步操作的最終完成(或失敗)及其結果。它會處於以下三個狀態之一:

1 Pending(待定):初始狀態,表示 Promise 尚未完成。

2 Resolved / Fulfilled(已解決):表示操作成功完成,並有結果返回。

3 Rejected(已拒絕):表示操作失敗,並有錯誤返回。

const promise = new Promise((resolve, reject) => {
  const success = true; // 這是操作的結果,假設為成功
  if (success) {
    resolve('成功了!');  // 表示成功並返回結果
  } else {
    reject('失敗了!');  // 表示失敗並返回錯誤
  }
});

resolve():表示異步操作成功並返回結果。 reject():表示異步操作失敗並返回錯誤。

2. Promise 的狀態變化

初始化狀態(Pending):當 Promise 創建時,它是 "待定" 的,尚未解決。

成功狀態(Fulfilled):當 resolve() 被調用時,Promise 變為成功狀態。

失敗狀態(Rejected):當 reject() 被調用時,Promise 變為失敗狀態。

3. .then() 的作用

Promise 提供了 .then() 方法來處理異步操作的結果。then() 方法接受兩個參數:

成功回調:Promise 成功時執行的函式。

失敗回調:Promise 失敗時執行的函式。

promise
  .then((result) => {
    console.log(result); // 成功時執行這裡的程式碼
  })
  .catch((error) => {
    console.log(error); // 失敗時執行這裡的程式碼
  });