龙空技术网

ES8新特性之Async和Await

编程鲍老师 419

前言:

现时你们对“asynch异步ajax”大致比较关注,姐妹们都想要了解一些“asynch异步ajax”的相关资讯。那么小编在网摘上搜集了一些对于“asynch异步ajax””的相关内容,希望大家能喜欢,兄弟们一起来了解一下吧!

概述:

async和await两种写法结合可以让异步代码看起来像同步代码一样;

简化异步函数的写法;

async函数

概述:

1.async函数的返回值为promise对象;

2.promise对象的结果由async函数的执行的返回值决定;

代码实现:

//async函数:异步函数async function fn() {    // return 123;//返回普通类型数据    //若报错,则返回的promise对象也是错误的    // throw new Error()    //若返回Promise对象,那么返回的结果就是Promise对象的结果    return new Promise((resolve, reject) => {        resolve("成功啦!");        reject("出错啦!");    });}const result = fn();console.log(result);//返回的结果一定是Promise对象result.then(value => {    console.log(value);}, reason => {    console.warn(reason);})
await表达式:

概述:

await必须写在async函数中;await右侧的表达式一般为promise对象;await返回promise成功的值;await的promise失败了,就会抛出异常,通过try...catch捕获;

代码实现:

//async函数+await表达式,异步函数//创建promise对象const p = new Promise((resolve, reject) => {    resolve("成功了!");});async function fn() {    //await返回的是promise成功值    let result = await p;    console.log(result);}fn();
运行结果:async和await读取文件案例:
//导入模块const fs = require('fs');//读取function readjust() {    return new Promise((resolve, reject) => {        fs.readFile("G:/code/ES6/1.txt", (err, data) => {            if (err) {                reject(err);            }            resolve(data);        });    });}function readjust2() {    return new Promise((resolve, reject) => {        fs.readFile("G:/code/ES6/2.txt", (err, data) => {            if (err) {                reject(err);            }            resolve(data);        });    });}function readjust3() {    return new Promise((resolve, reject) => {        fs.readFile("G:/code/ES6/3.txt", (err, data) => {            if (err) {                reject(err);            }            resolve(data);        });    });}//声明一个async函数async function main() {    //获取内容    let s1 = await readjust();    let s2 = await readjust2();    let s3 = await readjust3();    console.log(s1.toString());    console.log(s2.toString());    console.log(s3.toString());}main();
运行结果:async和await结合发送ajax请求:
//async和await结合发送ajax请求function sendAjax(url) {    return new Promise((resolve, reject) => {        //1.创建对象        const xhr = new XMLHttpRequest();        //2.初始化        xhr.open('get', url);        //3.发送        xhr.send();        //4.事件绑定        xhr.onreadystatechange = function () {            if (xhr.status == 1) {                //成功                resolve(xhr.response);            }            else {                //失败                reject(xhr.response);            }        }    })}//测试let url = ";;// const result = sendAjax(url);// result.then(value => {//     console.log(value);// }, reason => {//     console.log(reason);// });//使用async和await测试async function main() {    let result = sendAjax(url);    console.log(result);}
对象方法扩展:Object.values、Object. entries和 Object.getOwnPropertyDescriptors:Object.values()方法:返回一个给对象的所有枚举属性值的数组;Object.entries()方法:返回一个给定对象自身遍历[key,value]的数组;Object.getOwnPropertyDescriptors()该方法:返回指定对象所有自身属性的描述对象;代码实现:
//对象扩展let shool = {    name: '张三',    age: 24,    sex: '男'}//原始数据console.log(shool);//获取对象所有键console.log(Object.keys(shool));//获取所有的值console.log(Object.values(shool));//获取对象entriesconsole.log(Object.entries(shool));//创建mapconst map = new Map(Object.entries(shool))console.log(map);console.log(map.get("name"));//返回指定对象的自身的所有属性console.log(Object.getOwnPropertyDescriptors(shool));//参考内容const obj = Object.create(null, {    name: {        //设置值        value: '张三',        //属性特性        writable: true,        configuration: true,        enumerable: true    }});console.log(obj);
运行结果:

标签: #asynch异步ajax #ajax await