写在开头
ES6
常用但被忽略的方法 系列文章,整理作者认为一些日常开发可能会用到的一些方法、使用技巧和一些应用场景,细节深入请查看相关内容连接,欢迎补充交流。
相关文章
- ES6常用但被忽略的方法(第一弹解构赋值和数值)
- ES6常用但被忽略的方法(第二弹函数、数组和对象)
- ES6常用但被忽略的方法(第三弹Symbol、Set 和 Map )
- ES6常用但被忽略的方法(第四弹Proxy和Reflect)
- ES6常用但被忽略的方法(第五弹Promise和Iterator)
- ES6常用但被忽略的方法(第六弹Generator )
- ES6常用但被忽略的方法(第八弹Class)
- ES6常用但被忽略的方法(第九弹Module)
- ES6常用但被忽略的方法(第十弹项目开发规范)
- ES6常用但被忽略的方法(第十一弹Decorator)
- 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
命令有点像,交出代码的执行权给其他的模块加载,等异步操作完成后,再拿回执行权,继续向下执行。
- 上面代码有三个模块,最后的