ES6常用但被忽略的方法(第七弹async)

    技术2022-07-11  84

    写在开头

    ES6常用但被忽略的方法 系列文章,整理作者认为一些日常开发可能会用到的一些方法、使用技巧和一些应用场景,细节深入请查看相关内容连接,欢迎补充交流。

    相关文章

    ES6常用但被忽略的方法(第一弹解构赋值和数值) ES6常用但被忽略的方法(第二弹函数、数组和对象) ES6常用但被忽略的方法(第三弹Symbol、Set 和 Map ) ES6常用但被忽略的方法(第四弹Proxy和Reflect) ES6常用但被忽略的方法(第五弹Promise和Iterator) ES6常用但被忽略的方法(第六弹Generator )

    async 函数

    ES6-async 函数

    介绍

    async 函数是 Generator 函数的语法糖。

    const fs = require(‘fs’);

    const readFile = function (fileName) { return new Promise(function (resolve, reject) { fs.readFile(fileName, function(error, data) { if (error) return reject(error); resolve(data); }); }); }; // Generator函数写法 const gen = function* () { const f1 = yield readFile(’/etc/fstab’); const f2 = yield readFile(’/etc/shells’); console.log(f1.toString()); console.log(f2.toString()); }; // async 函数写法 const asyncReadFile = async function () { const f1 = await readFile(’/etc/fstab’); const f2 = await readFile(’/etc/shells’); console.log(f1.toString()); console.log(f2.toString()); }; 复制代码 async函数对 Generator 函数的改进:

    Generator 函数的执行必须靠执行器,所以才有了co模块(基于 ES6 的 Generator 和 yield ,让我们能用同步的形式编写异步代码),而async函数自带执行器。(async函数的执行,与普通函数一模一样,只要一行。)

    asyncReadFile(); 复制代码 Generator 函数,需要调用next方法,或者用co模块,才能真正执行,得到最后结果。

    const gg = gen(); gg.next() 复制代码 更好的语义。async和await,比起*和yield,语义更清楚。async表示函数里有异步操作,await表示紧跟在后面的表达式需要等待结果。 更广的适用性。co模块约定,yield命令后面只能是 Thunk 函数或 Promise 对象,而async函数的await命令后面,可以是 Promise 对象和原始类型的值(数值、字符串和布尔值,但这时会自动转成立即 resolved 的 Promise 对象)。 返回值是 Promise。async函数的返回值是 Promise 对象,这比 Generator 函数的返回值是 Iterator 对象方便很多。

    使用

    基操

    async函数返回一个 Promise对象,可以使用then方法添加回调函数。async函数内部return语句返回的值,会成为then方法回调函数的参数。 async函数内部抛出错误,会导致返回的 Promise 对象变为reject状态。抛出的错误对象会被catch方法回调函数接收到。

    async function getName() { return ‘detanx’; } getName().then(val => console.log(val)) // “detanx”

    // 抛出错误 async function f() { throw new Error(‘出错了’); }

    f().then( v => console.log(v), e => console.log(e) ) // Error: 出错了 复制代码 使用方式// 函数声明 async function foo() {}

    // 函数表达式 const foo = async function () {};

    // 对象的方法 let obj = { async foo() {} }; obj.foo().then(…)

    // 箭头函数 const foo = async () => {};

    // Class 的方法 class Storage { constructor() { this.cachePromise = caches.open(‘avatars’); }

    async getAvatar(name) { const cache = await this.cachePromise; return cache.match(/avatars/${name}.jpg); } }

    const storage = new Storage(); storage.getAvatar(‘jake’).then(…); 复制代码 状态变化

    async函数返回的 Promise 对象,必须等到内部所有await命令后面的 Promise 对象执行完,才会发生状态改变,除非遇到return语句或者抛出错误。

    await 命令

    正常情况下,await命令后面是一个 Promise 对象,返回该对象的结果。如果不是 Promise 对象,就直接返回对应的值。

    async function getName() { return ‘detanx’; } getName().then(val => console.log(val)) // “detanx” 复制代码 另一种情况是,await命令后面是一个thenable对象(定义了then方法的对象),那么await会将其等同于 Promise 对象。

    class Sleep { constructor(timeout) { this.timeout = timeout; } then(resolve, reject) { const startTime = Date.now(); setTimeout( () => resolve(Date.now() - startTime), this.timeout ); } }

    (async () => { const sleepTime = await new Sleep(1000); console.log(sleepTime); })(); // 1000 复制代码 任何一个await语句后面的 Promise 对象变为reject状态,那么整个async函数都会中断执行。async function f() { await Promise.reject(‘出错了’); await Promise.resolve(‘hello world’); // 不会执行 } 复制代码 前一个异步操作失败,也不要中断后面的异步操作。

    await放在try…catch里面

    async function f() { try { await Promise.reject(‘出错了’); } catch(e) { } return await Promise.resolve(‘detanx’); }

    f() .then(v => console.log(v)) // detanx 复制代码 await后面的 Promise 对象再跟一个catch方法,处理前面可能出现的错误。

    async function f() { await Promise.reject(‘出错了’) .catch(e => console.log(e)); return await Promise.resolve(‘detanx’); }

    f() .then(v => console.log(v)) // 出错了 // detanx 复制代码

    使用注意点

    await命令后面的Promise对象,运行结果可能是rejected,所以最好把await命令放在try…catch代码块中。 多个await命令后面的异步操作,如果不存在继发关系,最好让它们同时触发。

    // 写法一 let [foo, bar] = await Promise.all([getFoo(), getBar()]);

    // 写法二 let fooPromise = getFoo(); let barPromise = getBar(); let foo = await fooPromise; let bar = await barPromise; 复制代码 await命令只能用在async函数之中,如果用在普通函数,就会报错。正确的写法是采用for循环或者使用数组的reduce方法。希望多个请求并发执行,可以使用Promise.all或者Promise.allSettled方法。

    async function dbFuc(db) { let docs = [{}, {}, {}];

    // 报错,await的上一级函数不是async函数 docs.forEach(function (doc) { await db.post(doc); }); => for循环 for (let doc of docs) { await db.post(doc); } => 数组的reduce方法 await docs.reduce(async (_, doc) => { await _; await db.post(doc); }, undefined); } 复制代码 async 函数可以保留运行堆栈。

    const a = () => { b().then(() => c()); }; 复制代码

    上面代码中,函数a内部运行了一个异步任务b()。当b()运行的时候,函数a()不会中断,而是继续执行。等到b()运行结束,可能a()早就运行结束,b()所在的上下文环境已经消失。如果b()或c()报错,错误堆栈将不包括a()。

    现在将这个例子改成async函数。

    const a = async () => { await b(); c(); }; 复制代码 上面代码中,b()运行的时候,a()是暂停执行,上下文环境都保存着。一旦b()或c()报错,错误堆栈将包括a()。

    实现

    async 函数的实现原理,就是将 Generator 函数和自动执行器,包装在一个函数里。

    async function fn(args) { // … } // 等同于 function fn(args) { return spawn(function* () { // … }); } 复制代码 所有的async函数都可以写成上面的第二种形式,其中的spawn函数就是自动执行器。下面spawn函数的实现,基本就是前文自动执行器的翻版。

    function spawn(genF) { return new Promise(function(resolve, reject) { const gen = genF(); function step(nextF) { let next; try { next = nextF(); } catch(e) { return reject(e); } if(next.done) { return resolve(next.value); } Promise.resolve(next.value).then(function(v) { step(function() { return gen.next(v); }); }, function(e) { step(function() { return gen.throw(e); }); }); } step(function() { return gen.next(undefined); }); }); } 复制代码异步处理方法的比较

    传统方法,ES6 诞生以前,异步编程的方法,大概有下面四种。

    回调函数 事件监听 发布/订阅 Promise 对象

    通过一个例子,主要来看 Promise、Generator 函数与async 函数的比较,其他的不太熟悉的可以自己去查相关的资料。

    假定某个 DOM 元素上面,部署了一系列的动画,前一个动画结束,才能开始后一个。如果当中有一个动画出错,就不再往下执行,返回上一个成功执行的动画的返回值。

    Promise 的写法

    function chainAnimationsPromise(elem, animations) { // 变量ret用来保存上一个动画的返回值 let ret = null; // 新建一个空的Promise let p = Promise.resolve();

    // 使用then方法,添加所有动画 for(let anim of animations) { p = p.then(function(val) { ret = val; return anim(elem); }); } // 返回一个部署了错误捕捉机制的Promise return p.catch(function(e) { /* 忽略错误,继续执行 */ }).then(function() { return ret; }); } 复制代码 一眼看上去,代码完全都是 Promise 的 API(then、catch等等),操作本身的语义反而不容易看出来。

    Generator 函数的写法。

    function chainAnimationsGenerator(elem, animations) {

    return spawn(function*() { let ret = null; try { for(let anim of animations) { ret = yield anim(elem); } } catch(e) { /* 忽略错误,继续执行 */ } return ret; }); } 复制代码 语义比 Promise 写法更清晰,用户定义的操作全部都出现在spawn函数的内部。问题在于,必须有一个任务运行器,自动执行 Generator 函数,上面代码的spawn函数就是自动执行器,它返回一个 Promise 对象,而且必须保证yield语句后面的表达式,必须返回一个 Promise。

    async 函数的写法。

    async function chainAnimationsAsync(elem, animations) { let ret = null; try { for(let anim of animations) { ret = await anim(elem); } } catch(e) { /* 忽略错误,继续执行 */ } return ret; } 复制代码 Async 函数的实现最简洁,最符合语义,几乎没有语义不相关的代码。

    所有的异步处理方法存在即合理,没有那个最好,只有最合适,在处理不同的实际情况时,我们选择最适合的处理方法即可。

    实例

    实际开发中,经常遇到一组异步操作,需要按照顺序完成。比如,依次远程读取一组 URL,然后按照读取的顺序输出结果。

    Promise 的写法。

    function logInOrder(urls) { // 远程读取所有URL const textPromises = urls.map(url => { return fetch(url).then(response => response.text()); });

    // 按次序输出 textPromises.reduce((chain, textPromise) => { return chain.then(() => textPromise) .then(text => console.log(text)); }, Promise.resolve()); } 复制代码 上面代码使用fetch方法,同时远程读取一组 URL。每个fetch操作都返回一个 Promise 对象,放入textPromises数组。然后,reduce方法依次处理每个 Promise 对象,然后使用then,将所有 Promise 对象连起来,因此就可以依次输出结果。

    async 函数实现。

    async function logInOrder(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); } } 复制代码 上面代码中,虽然map方法的参数是async函数,但它是并发执行的,因为只有async函数内部是继发执行,外部不受影响。后面的for…of循环内部使用了await,因此实现了按顺序输出。

    顶级 await

    现在 await 命令只能出现在 async 函数内部,否则都会报错。有一个语法提案(目前提案处于Status: Stage 3),允许在模块的顶层独立使用 await 命令,使得上面那行代码不会报错了。这个提案的目的,是借用 await 解决模块异步加载的问题。

    模块awaiting.js的输出值output,取决于异步操作。

    // awaiting.js let output; (async function1 main() { const dynamic = await import(someMission); const data = await fetch(url); output = someProcess(dynamic.default, data); })(); export { output }; 复制代码 加载awaiting.js模块

    // usage.js import { output } from “./awaiting.js”;

    function outputPlusValue(value) { return output + value } console.log(outputPlusValue(100)); setTimeout(() => console.log(outputPlusValue(100), 1000); 复制代码 outputPlusValue()的执行结果,完全取决于执行的时间。如果awaiting.js里面的异步操作没执行完,加载进来的output的值就是undefined。

    目前的解决方法,就是让原始模块输出一个 Promise 对象,从这个 Promise 对象判断异步操作有没有结束。// usage.js import promise, { output } from “./awaiting.js”;

    function outputPlusValue(value) { return output + value } promise.then(() => { console.log(outputPlusValue(100)); setTimeout(() => console.log(outputPlusValue(100), 1000); }); 复制代码 上面代码中,将awaiting.js对象的输出,放在promise.then()里面,这样就能保证异步操作完成以后,才去读取output。 这种写法比较麻烦,等于要求模块的使用者遵守一个额外的使用协议,按照特殊的方法使用这个模块。一旦你忘了要用 Promise 加载,只使用正常的加载方法,依赖这个模块的代码就可能出错。而且,如果上面的usage.js又有对外的输出,等于这个依赖链的所有模块都要使用 Promise 加载。

    顶层的await命令,它保证只有异步操作完成,模块才会输出值。// awaiting.js const dynamic = import(someMission); const data = fetch(url); export const output = someProcess((await dynamic).default, await data);

    // usage.js import { output } from “./awaiting.js”; function outputPlusValue(value) { return output + value }

    console.log(outputPlusValue(100)); setTimeout(() => console.log(outputPlusValue(100), 1000); 复制代码 上面代码中,两个异步操作在输出的时候,都加上了await命令。只有等到异步操作完成,这个模块才会输出值。

    顶层await的一些使用场景。// import() 方法加载 const strings = await import(/i18n/${navigator.language});

    // 数据库操作 const connection = await dbConnector();

    // 依赖回滚 let jQuery; try { jQuery = await import(‘https://cdn-a.com/jQuery’); } catch { jQuery = await import(‘https://cdn-b.com/jQuery’); } 复制代码 如果加载多个包含顶层await命令的模块,加载命令是同步执行的。// x.js console.log(“X1”); await new Promise(r => setTimeout(r, 1000)); console.log(“X2”);

    // y.js console.log(“Y”);

    // z.js import “./x.js”; import “./y.js”; console.log(“Z”); 复制代码 上面代码有三个模块,最后的z.js加载x.js和y.js,打印结果是X1、Y、X2、Z。这说明,z.js并没有等待x.js加载完成,再去加载y.js。 顶层的await命令有点像,交出代码的执行权给其他的模块加载,等异步操作完成后,再拿回执行权,继续向下执行。

    Processed: 0.016, SQL: 9