ES7新优点
Array.prototype.includes:检查和字符串中与否包涵某原素,回到bool值const arr = [Foo,Bar,Crushdada];
console.log(ar.includes(Foo)); //true
ES7容许用函数排序算式console.log(2 ** 10); //1024
console.log(Math.pow(2,10)) //ES5方法
async和await:捷伊触发器程式设计软件系统
async函数
它像两个Promise的句法糖,无须再限于new两个Promise,接着在里头反射出统计数据给.then方式的文档格式,但,通常async是用来和await紧密结合采用的!
async函数的codice为promise第一类promise第一类的结论由async函数继续执行的codice下定决心await函数
await要写在async函数左侧的函数通常为promise第一类 它回到的是promise 获得成功的值await的Promise失利了,就会放出极度,须要try…catch捕捉它const p = new Promise((resolve, reject) => {
resolve(“got it!”);
//reject(“shibai”);
});
async function fn() {
try {
let res = await p;
console.log(res);
} catch (rea) {
console.log(rea);
}
}
fn();
async+await加载多文档应用领域
关键步骤:
引入fs模块:调用readFile方式封装读取:用不同的的函数加载,回到各自的Promise第一类声明两个async函数:在其中采用await+try…catch 统一处理function readFile1() {
return new Promise(function (resolve, reject) {
fs.readFile(“../../test/1.txt”, (err, data) => {
if (err) reject(err);
resolve(data);
});
});
}
function readFile2() {···} //此处省略,和readFile1相比只改了路径
function readFile3() {···} //同上
async function deal() {
try {
let res1 = await readFile1();
let res2 = await readFile2();
let res3 = await readFile3();
console.log(res1.toString());
console.log(res2.toString());
console.log(res3.toString());
} catch (rea) {
console.log(rea); // console.log(错误!);
}
}
deal();
若修改成两个错误路径“22.txt”,那么catch到的错误信息为你也可以不回到这个错误,仅回到“错误!”
async+await封装Ajax!
写两个请求函数,回到两个new 出来的Promise第一类,在其其中发送Ajax请求写两个async函数,用以调用上述函数并用await接收codicefunction ajax(url) {
return new Promise((resolve, reject) => {
const x = new XMLHttpRequest();
x.open(“GET”, url);
x.send();
x.onreadystatechange = () => {
if (x.readyState === 4) {
if (x.status >= 200 && x.status < 300) {
resolve(x.response);
} else {
reject(x.status);
}
}
};
});
}
//采用promise.then的形式
// ajax(“https://api.apiopen.top/getJoke”).then(
// (val) => {console.log(res);},
// (rea) => {console.log(rea);}
// );
async function receive(url) {
try {
let res = await ajax(url);
console.log(JSON.parse(res));
} catch (rea) {
console.log(rea);
}
}
receive(“https://api.apiopen.top/getJoke”);