首頁 > web前端 > js教程 > 主體

ES6中Async函數的詳細介紹(附範例)

不言
發布: 2018-10-24 10:33:49
轉載
2662 人瀏覽過

這篇文章帶給大家的內容是關於ES6中Async函數的詳細介紹(附範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

async

ES2017 標準引入了 async 函數,使得非同步操作變得更加方便。

在非同步處理上,async 函數就是 Generator 函數的語法糖。

舉個例子:

// 使用 generator
var fetch = require('node-fetch');
var co = require('co');

function* gen() {
    var r1 = yield fetch('https://api.github.com/users/github');
    var json1 = yield r1.json();
    console.log(json1.bio);
}

co(gen);
登入後複製

當你使用async 時:

// 使用 async
var fetch = require('node-fetch');

var fetchData = async function () {
    var r1 = await fetch('https://api.github.com/users/github');
    var json1 = await r1.json();
    console.log(json1.bio);
};

fetchData();
登入後複製

其實async 函數的實作原理,就是將Generator 函數和自動執行器,包裝在一個函數裡。

async function fn(args) {
  // ...
}

// 等同于

function fn(args) {
  return spawn(function* () {
    // ...
  });
}
登入後複製

spawn 函式指的是自動執行器,就比方說 co。

再加上 async 函數傳回一個 Promise 對象,你也可以理解為 async 函數是基於 Promise 和 Generator 的一層封裝。

async 與Promise

嚴謹的說,async 是一種語法,Promise 是一個內建對象,兩者並不具備可比性,更何況async 函數也傳回一個Promise 物件…

這裡主要是展示一些場景,使用async 會比使用Promise 更優雅的處理非同步流程。

1. 程式碼更簡潔

/**
 * 示例一
 */
function fetch() {
  return (
    fetchData()
    .then(() => {
      return "done"
    });
  )
}

async function fetch() {
  await fetchData()
  return "done"
};
登入後複製
/**
 * 示例二
 */
function fetch() {
  return fetchData()
  .then(data => {
    if (data.moreData) {
        return fetchAnotherData(data)
        .then(moreData => {
          return moreData
        })
    } else {
      return data
    }
  });
}

async function fetch() {
  const data = await fetchData()
  if (data.moreData) {
    const moreData = await fetchAnotherData(data);
    return moreData
  } else {
    return data
  }
};
登入後複製
/**
 * 示例三
 */
function fetch() {
  return (
    fetchData()
    .then(value1 => {
      return fetchMoreData(value1)
    })
    .then(value2 => {
      return fetchMoreData2(value2)
    })
  )
}

async function fetch() {
  const value1 = await fetchData()
  const value2 = await fetchMoreData(value1)
  return fetchMoreData2(value2)
};
登入後複製

2. 錯誤處理

function fetch() {
  try {
    fetchData()
      .then(result => {
        const data = JSON.parse(result)
      })
      .catch((err) => {
        console.log(err)
      })
  } catch (err) {
    console.log(err)
  }
}
登入後複製

在這段程式碼中,try/catch 能捕捉fetchData() 中的一些Promise 建構錯誤,但是不能捕獲JSON.parse 拋出的異常,如果要處理JSON.parse 拋出的異常,需要添加catch 函數重複一遍異常處理的邏輯。

在實際專案中,錯誤處理邏輯可能會很複雜,這會導致冗餘的程式碼。

async function fetch() {
  try {
    const data = JSON.parse(await fetchData())
  } catch (err) {
    console.log(err)
  }
};
登入後複製

async/await 的出現使得 try/catch 就可以捕捉同步和非同步的錯誤。

3. 偵錯

const fetchData = () => new Promise((resolve) => setTimeout(resolve, 1000, 1))
const fetchMoreData = (value) => new Promise((resolve) => setTimeout(resolve, 1000, value + 1))
const fetchMoreData2 = (value) => new Promise((resolve) => setTimeout(resolve, 1000, value + 2))

function fetch() {
  return (
    fetchData()
    .then((value1) => {
      console.log(value1)
      return fetchMoreData(value1)
    })
    .then(value2 => {
      return fetchMoreData2(value2)
    })
  )
}

const res = fetch();
console.log(res);
登入後複製

ES6中Async函數的詳細介紹(附範例)

#因為then 中的程式碼是非同步執行,所以當你打斷點的時候,程式碼不會依序執行,尤其當你使用step over 的時候,then 函數會直接進入下一個then 函數。

const fetchData = () => new Promise((resolve) => setTimeout(resolve, 1000, 1))
const fetchMoreData = () => new Promise((resolve) => setTimeout(resolve, 1000, 2))
const fetchMoreData2 = () => new Promise((resolve) => setTimeout(resolve, 1000, 3))

async function fetch() {
  const value1 = await fetchData()
  const value2 = await fetchMoreData(value1)
  return fetchMoreData2(value2)
};

const res = fetch();
console.log(res);
登入後複製

ES6中Async函數的詳細介紹(附範例)

而使用 async 的時候,則可以像偵錯同步程式碼一樣除錯。

async 地獄

async 地獄主要是指開發者貪圖語法上的簡潔而讓原本可以並行執行的內容變成了順序執行,從而影響了性能,但用地獄形容有點誇張了點…

例子一

舉例:

(async () => {
  const getList = await getList();
  const getAnotherList = await getAnotherList();
})();
登入後複製

getList() 和getAnotherList() 其實沒有依賴關係,但現在的這種寫法,雖然簡潔,卻導致了getAnotherList() 只能在getList() 回傳後才會執行,導致了多一倍的請求時間。

為了解決這個問題,我們可以改成這樣:

(async () => {
  const listPromise = getList();
  const anotherListPromise = getAnotherList();
  await listPromise;
  await anotherListPromise;
})();
登入後複製

也可以使用Promise.all():

(async () => {
  Promise.all([getList(), getAnotherList()]).then(...);
})();
登入後複製

範例二

當然上面這個例子比較簡單,我們再來擴充一下:

(async () => {
  const listPromise = await getList();
  const anotherListPromise = await getAnotherList();

  // do something

  await submit(listData);
  await submit(anotherListData);

})();
登入後複製

因為await 的特性,整個例子有明顯的先後順序,然而getList() 和getAnotherList() 其實並無依賴,submit(listData) 和submit( anotherListData) 也沒有依賴關係,那麼對於這種例子,我們該怎麼改寫呢?

基本上分為三個步驟:

1. 找出依賴關係

在這裡,submit(listData) 需要在getList() 之後,submit(anotherListData) 需要在anotherListPromise() 之後。

2. 將互相依賴的語句包裹在async 函數中

async function handleList() {
  const listPromise = await getList();
  // ...
  await submit(listData);
}

async function handleAnotherList() {
  const anotherListPromise = await getAnotherList()
  // ...
  await submit(anotherListData)
}
登入後複製

3.並發執行async 函數

async function handleList() {
  const listPromise = await getList();
  // ...
  await submit(listData);
}

async function handleAnotherList() {
  const anotherListPromise = await getAnotherList()
  // ...
  await submit(anotherListData)
}

// 方法一
(async () => {
  const handleListPromise = handleList()
  const handleAnotherListPromise = handleAnotherList()
  await handleListPromise
  await handleAnotherListPromise
})()

// 方法二
(async () => {
  Promise.all([handleList(), handleAnotherList()]).then()
})()
登入後複製

繼發與並發

問題:給定一個URL 數組,如何實現介面的繼發和並發?

async 繼發實作:

// 继发一
async function loadData() {
  var res1 = await fetch(url1);
  var res2 = await fetch(url2);
  var res3 = await fetch(url3);
  return "whew all done";
}
登入後複製
// 继发二
async function loadData(urls) {
  for (const url of urls) {
    const response = await fetch(url);
    console.log(await response.text());
  }
}
登入後複製

async 並發實作:

// 并发一
async function loadData() {
  var res = await Promise.all([fetch(url1), fetch(url2), fetch(url3)]);
  return "whew all done";
}
登入後複製
// 并发二
async function loadData(urls) {
  // 并发读取 url
  const textPromises = urls.map(async url => {
    const response = await fetch(url);
    return response.text();
  });

  // 按次序输出
  for (const textPromise of textPromises) {
    console.log(await textPromise);
  }
}
登入後複製

async 錯誤捕捉

#儘管我們可以使用try catch 擷取錯誤,但當我們需要捕獲多個錯誤並做不同的處理時,很快try catch 就會導致程式碼雜亂,就例如:

async function asyncTask(cb) {
    try {
       const user = await UserModel.findById(1);
       if(!user) return cb('No user found');
    } catch(e) {
        return cb('Unexpected error occurred');
    }

    try {
       const savedTask = await TaskModel({userId: user.id, name: 'Demo Task'});
    } catch(e) {
        return cb('Error occurred while saving task');
    }

    if(user.notificationsEnabled) {
        try {
            await NotificationService.sendNotification(user.id, 'Task Created');
        } catch(e) {
            return cb('Error while sending notification');
        }
    }

    if(savedTask.assignedUser.id !== user.id) {
        try {
            await NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you');
        } catch(e) {
            return cb('Error while sending notification');
        }
    }

    cb(null, savedTask);
}
登入後複製

為了簡化這種錯誤的捕獲,我們可以給await 後的promise物件加入catch 函數,為此我們需要寫一個helper:

// to.js
export default function to(promise) {
   return promise.then(data => {
      return [null, data];
   })
   .catch(err => [err]);
}
登入後複製

整個錯誤捕獲的程式碼可以簡化為:

import to from './to.js';

async function asyncTask() {
     let err, user, savedTask;

     [err, user] = await to(UserModel.findById(1));
     if(!user) throw new CustomerError('No user found');

     [err, savedTask] = await to(TaskModel({userId: user.id, name: 'Demo Task'}));
     if(err) throw new CustomError('Error occurred while saving task');

    if(user.notificationsEnabled) {
       const [err] = await to(NotificationService.sendNotification(user.id, 'Task Created'));
       if (err) console.error('Just log the error and continue flow');
    }
}
登入後複製

async 的一些討論

async 會取代Generator嗎?

Generator 本來是用作生成器,使用Generator 處理非同步請求只是一個比較hack 的用法,在非同步方面,async 可以取代Generator,但是async 和Generator 兩個語法本身是用來解決不同的問題的。

async 會取代 Promise 嗎?

  1. async 函數回傳一個Promise 物件

  2. 面對複雜的非同步流程,Promise 提供的all 和race 會更好用

  3. Promise 本身就是一個對象,所以可以在程式碼中任意傳遞

  4. #async 的支援率還很低,即使有Babel,編譯後也要增加1000 行左右。


##

以上是ES6中Async函數的詳細介紹(附範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:segmentfault.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!