应用 async 函数,只须要像编写同步代码那样调用 asynchronousOperation:
- async function doAsyncOp () {
- var val = await asynchronousOperation();
- val = await asynchronousOperation(val);
- val = await asynchronousOperation(val);
- return await asynchronousOperation(val);
- };
- function getAllFiles(fileNames) {
- return Promise.all(
- fileNames.map(function(fileName) {
- return getFileAsync(fileName).then(function(file) {
- return parse(file);
- });
- })
- );
- }
甚至最后的 return 语句中都不须要应用 await,因为用或不消,它都返回了包含了可处理终值的 Promise。
Promise 还有另一个巨大年夜的特点,它们可以同时进行多个异步操作,等他们全部完成之后再持续进行其它事宜。ES2015 规范中供给了 Promise.all(),就是用来干这个工作的。
- function doAsyncOp() {
- return Promise.all([
- asynchronousOperation(),
- asynchronousOperation()
- ]).then(function
推荐阅读
说到可视化,就不得不说一下大年夜数据,毕竟可视化是解决大年夜数据的一种高效的手段,而如今人人都在谈论大年夜数据,大年夜数据 ≠ 稀有据 ≠ 数据量大年夜, 离谱的是,如今就连>>>详细阅读
本文标题:用Async函数简化异步代码
地址:http://www.17bianji.com/lsqh/34848.html
1/2 1