async/await

限定程式依序(同步)執行

async/await

  • ES7中提供的異步解決方案(要搭配promise)(可增加promise的可讀性),在迴圈中使用更加靈活簡潔。

  • async

    • async本質上是對 promise 的封裝

    • 對async來說await不是必須的,但await一定要在async內

  • await

    • await 會等待這段函式完成後在往下繼續執行,這是一個卡住的概念

    • await一定會回傳 promise 物件(若是字串,會自動轉為promise物件)

    • 當await中的某個 Promise 變成 reject 時,函數暫停執行,後面的程式不會執行。

// === 範例一 ===
// 定義暫停功能,要當成 await 所以要返回 promise
var sleep = function (time) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve();
        }, time);
    })
};

var start = async function () {
    console.log('start');
    
    await sleep(3000);
    
    console.log('end');
};

start();
//控制台先输出start,稍等3秒后,输出了end。


// === 範例二 ===
async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    const data = await response.json();
    console.log("資料獲取成功:", data);
  } catch (error) {
    console.error("獲取資料時出錯:", error);
  }
}

fetchData();

Last updated

Was this helpful?