ES6基础知识(async 函数)
1.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 函数的星号(*)替换成async,将yield替换成await,async函数的返回值是 Promise 对象,这比 Generator 函数的返回值是 Iterator 对象方便多了。你可以用then方法指定下一步的操作。进一步说,async函数完全可以看作多个异步操作,包装成的一个 Promise 对象,而await命令就是内部then命令的语法糖。
2.async 函数有多种使用形式
// 函数声明
async function foo() {} // 函数表达式
const foo = async function () {}; // 对象的方法
let obj = { async foo() {} };
obj.foo().then(...) // 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(…); // 箭头函数
const foo = async () => {};
3.只有async函数内部的异步操作执行完,才会执行then方法指定的回调函数
async function getTitle(url) {
let response = await fetch(url);
let html = await response.text();
return html.match(/<title>([\s\S]+)<\/title>/i)[1];
}
getTitle('https://tc39.github.io/ecma262/').then(console.log);
上面代码中,函数getTitle内部有三个操作:抓取网页、取出文本、匹配页面标题。只有这三个操作全部完成,才会执行then方法里面的console.log。
4.按顺序完成异步操作,依次远程进行ajax请求,然后按照请求的顺序输出结果
let urls = [
'https://www.easy-mock.com/mock/5c73528306ffee27c6b2f0aa/testAerial/pointarr',
'https://www.easy-mock.com/mock/5b62549fbf26d2748cff3cf4/dashuju/visualize'
]; async function loader1(urls){//所有远程操作都是继发。只有前一个 URL 返回结果,才会去读取下一个 URL
for(let url of urls){
const response = await $.getJSON(url).then((res) => res);
console.log(response);//ajax先后请求并返回结果
}
}
loader1(urls);
5.并发发出远程ajax请求,同时输出结果
let urls = [
'https://www.easy-mock.com/mock/5c73528306ffee27c6b2f0aa/testAerial/pointarr',
'https://www.easy-mock.com/mock/5b62549fbf26d2748cff3cf4/dashuju/visualize'
]; async function loader(urls){//map方法的参数是async函数,但它是并发执行的,因为只有async函数内部是继发执行,外部不受影响。后面的for..of循环内部使用了await,因此实现了按顺序输出
const results = urls.map(async url => {
const response = await $.getJSON(url).then((res) => res);
return response;
}); for(let text of results){
console.log(await text);//ajax一起请求同时返回结果
} }
loader(urls);
6.异步遍历器与同步遍历器
const asyncIterable = createAsyncIterable(['a', 'b']);
const asyncIterator = asyncIterable[Symbol.asyncIterator]();//部署异步遍历器接口 asyncIterator
.next()
.then(iterResult1 => {
console.log(iterResult1); // { value: 'a', done: false }
return asyncIterator.next();
})
.then(iterResult2 => {
console.log(iterResult2); // { value: 'b', done: false }
return asyncIterator.next();
})
.then(iterResult3 => {
console.log(iterResult3); // { value: undefined, done: true }
});
let arr = ['a', 'b', 'c'];
let iter = arr[Symbol.iterator]();//部署同步遍历器 iter.next() // { value: 'a', done: false }
iter.next() // { value: 'b', done: false }
iter.next() // { value: 'c', done: false }
iter.next() // { value: undefined, done: true }
备注:文中多数内容摘自阮一峰老师文章,仅供自我学习查阅。
ES6基础知识(async 函数)的更多相关文章
- es6学习笔记-async函数
1 前情摘要 前段时间时间进行项目开发,需求安排不是很合理,导致一直高强度的加班工作,这一个月不是常说的996,简直是936,还好熬过来了.在此期间不是刚学会了es6的promise,在项目有用到pr ...
- 深入浅出ES6教程『async函数』
大家好,本人名叫苏日俪格,大家叫我 (格格) 就好,在上一章节中我们学到了Symbol & generator的用法,下面我们一起来继续学习async函数: async [ə'zɪŋk]:这个 ...
- php面试笔记(5)-php基础知识-自定义函数及内部函数考点
本文是根据慕课网Jason老师的课程进行的PHP面试知识点总结和升华,如有侵权请联系我进行删除,email:guoyugygy@163.com 在面试中,考官往往喜欢基础扎实的面试者,而函数相关的考点 ...
- [C/C++基础知识] main函数的参数argc和argv
该篇文章主要是关于C++\C语言最基础的main函数的参数知识,是学习C++或C语言都必备的知识点.不知道你是否知道该知识?希望对大家有所帮助.一.main()函数参数通常我们在写主函数时都是void ...
- ES6中的async函数
一.概述 async 函数是 Generator 函数的语法糖 使用Generator 函数,依次读取两个文件代码如下 var fs = require('fs'); var readFile = f ...
- ES6学习之Async函数
定义:Async函数是一个异步操作函数,本质上,Async函数是Generator函数的语法糖.async函数就是将 Generator 函数的星号(*)替换成async,将yield替换成await ...
- 浅谈ES6中的Async函数
转载地址:https://www.cnblogs.com/sghy/p/7987640.html 定义:Async函数是一个异步操作函数,本质上,Async函数是Generator函数的语法糖.asy ...
- ES6基础知识(Generator 函数应用)
1.Ajax 是典型的异步操作,通过 Generator 函数部署 Ajax 操作,可以用同步的方式表达 function* main() { var result = yield request(& ...
- ES6基础知识(Generator 函数)
1.next().throw().return() 的共同点 next().throw().return()这三个方法本质上是同一件事,可以放在一起理解.它们的作用都是让 Generator 函数恢复 ...
随机推荐
- Redis之品鉴之旅(一)
Redis之品鉴之旅(一) 好知识就如好酒,需要我们坐下来,静静的慢慢的去品鉴.Redis作为主流nosql数据库,在提升性能的方面是不可或缺的.下面就拿好小板凳,我们慢慢的来一一品鉴. 1)redi ...
- Windows10通过WSL编译jdk12
Windows使用WSL编译OpenJDK 安装Ubuntu以及配置国内镜像 首选确保windows10已经安装了ubuntu 更换ubuntu20.04国内镜像,这里我选择的是阿里云镜像 sudo ...
- UE4技术总结——委托
UE4技术总结--委托 目录 UE4技术总结--委托 一.定义 二.用法 2.1 声明与调用委托 2.1.1 单播委托 2.1.1.a 声明 2.1.1.b 绑定 2.1.1.c 执行委托 2.1.1 ...
- 使用mobaXtrem显示CentOS图形
安装环境 yum install -y xorg-x11-xauth xorg-x11-fonts-* xorg-x11-font-utils xorg-x11-fonts-Type1 \mesa-l ...
- 洛谷4895 独钓寒江雪 (树哈希+dp+组合)
qwq 首先,如果是没有要求本质不同的话,那么还是比较简单的一个树形dp 我们令\(dp[i][0/1]\)表示是否\(i\)的子树,是否选\(i\)这个点的方案数. 一个比较显然的想法. \(dp[ ...
- Typora配置双击图片放大功能
在Typora中,默认没有点击图片放大功能,本文就教大家如何配置该功能. 我的环境版本 Typora版本:0.11.13 LightBox版本:2.11.3 下载LightBox 可以从Github下 ...
- Poetry(2)Poetry的基本使用方式
Poetry的基本使用 准备工作 如果你是在一个已有的项目里使用Poetry,你只需要执行 poetry init 命令来创建一个 pyproject.toml 文件: poetry init 可看到 ...
- 【UE4 C++ 基础知识】<10>资源的引用
2种引用方式 硬引用(Hard Reference) 即对象 A 引用对象 B,并导致对象 B 在对象 A 加载时加载 硬引用过多会导致运行时很多暂时用不到的资源也被加载到内存中 大量资源会导致进程阻 ...
- zuul过滤器filter 的编写
通过上一节(zuul的各种配置)的学习,我们学会了zuul路由的各种配置,这一节我们来实现一下zuul的过滤器功能.那么为什么需要用到zuul的过滤器呢?我们知道zuul是我们实现外部系统统一访问的入 ...
- lib库无法加载的情况分析
最近升级vs2017的时候遇到无法加载库的问题,在网上查找问题,网上给出可能有三种情况导致该问题:路径是否正确:库依赖是否齐全:库版本是否正确.最直接的方法就是用depends软件去查询,是否有模块有 ...