asynces2017 标准引入了 async 函数,使得异步操作变得更加方便。
在异步处理上,async 函数就是 generator 函数的语法糖。
举个例子:
// 使用 generatorvar 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 时:
// 使用 asyncvar 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);
因为 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);
而使用 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.jsexport 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 吗?async 函数返回一个 promise 对象
面对复杂的异步流程,promise 提供的 all 和 race 会更加好用
promise 本身是一个对象,所以可以在代码中任意传递
async 的支持率还很低,即使有 babel,编译后也要增加 1000 行左右。
以上就是es6中async函数的详细介绍(附示例)的详细内容。