ES8 新特性

ES8 新特性

async 函数

  • 返回的结果如果不是一个 Promise 类型的对象,返回值就是成功

    async function fn() {
      return "尚硅谷";
    }
    
    const result = fn();
    console.log(result); // promise函数 {<fulfilled>: '尚硅谷'}
    
  • 抛出错误,返回的结果是一个失败的 Promise

    async function fn() {
      throw new Error("出错了");
    }
    
    const result = fn();
    console.log(result); // promise函数 {<rejected>: '出错了'}
    
  • 返回的结果如果是一个 Promise 对象

    async function fn() {
      return new Promise((resolve, reject) => {
        // resolve('成功的数据');
        reject("失败的数据");
      });
    }
    
    const result = fn();
    // 调用 then
    result.then(
      (value) => {
        console.log(value); // {<fulfilled>: '成功的数据'}
      },
      (reason) => {
        console.warn(reason); // {<rejected>: '失败的数据'}
      }
    );
    

await 表达式

1.await 基本语法

// 创建 Promise 对象
const p = new Promise((resolve, reject) => {
  // resolve('用户数据');
  reject("失败了");
});

// await 要放在 async 函数中
// await 后跟 Promise 函数
// 通过 try-catch 捕获 reject
async function main() {
  try {
    let result = await p;
    console.log(result); // 用户数据
  } catch (e) {
    console.log(e); // 失败了
  }
}

main();

2.async 与 await 结合读取文件

// 1. 引入 fs 模块
const fs = require("fs");

// 读取为学
function readWeixue() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      fs.readFile("../resources/为学.txt", (err, data) => {
        if (err) reject(err);
        resolve(data);
      });
    }, 3000);
  });
}

// 读取悯农
function readMinnong() {
  return new Promise((resolve, reject) => {
    fs.readFile("../resources/悯农.txt", (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
}

// 读取插秧诗
function readChayangshi() {
  return new Promise((resolve, reject) => {
    fs.readFile("../resources/插秧诗.txt", (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
}

// 声明一个 async 函数
async function main() {
  let weixue = await readWeixue(); // 方法返回才会执行下一个

  let minnong = await readMinnong();

  let chayangshi = await readChayangshi();

  console.log(weixue.toString());
  console.log(minnong.toString());
  console.log(chayangshi.toString());
}

main();

3.async 与 await 结合发送 AJAX 请求

// 发送 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.readyState === 4) {
        if (xhr.status === 200 && xhr.status < 300) {
          resolve(xhr.response);
        } else {
          reject(xhr.status);
        }
      }
    };
  });
}

/* // promise then方法测试
sendAJAX('https://api.apiopen.top/getJoke').then(value => {
  console.log(value)
}, reason => { }) */

// async 与 await 测试
async function main() {
  let result = await sendAJAX("https://api.apiopen.top/getJoke");
  console.log(result);

  let tianqi = await sendAJAX(
    "https://tianqiapi.com/api/?version=v1&city=深圳&appid=23941491&appsecret=TXoD5e8P"
  );
  console.log(tianqi);

  let result2 = await sendAJAX(
    "https://v0.yiketianqi.com/aqi/rankcity?appid=23941491&appsecret=TXoD5e8P"
  );
  console.log(result2);
}
main();

对象方法扩展

  • 获取对象所有的键 Object.keys()

    const school = {
      name: "尚硅谷",
      cities: ["北京", "上海", "深圳"],
      xueke: ["前段", "Vue", "Axios", "Java"],
    };
    
    // 获取对象所有的键
    console.log(Object.keys(school)); // ["name","cities","xueke"]
    
  • 获取对象所有的值 Object.values()

    const school = {
      name: "尚硅谷",
      cities: ["北京", "上海", "深圳"],
      xueke: ["前端", "Vue", "Axios", "Java"],
    };
    
    // 获取对象所有的值
    console.log(Object.values(school)); // ['尚硅谷', ['北京', '上海', '深圳'], ['前端', 'Vue', 'Axios', 'Java']]
    
  • 将对象转换为键值对数组 Object.entries()

    const school = {
      name: "尚硅谷",
      cities: ["北京", "上海", "深圳"],
      xueke: ["前段", "Vue", "Axios", "Java"],
    };
    
    // entries 将对象转换为键值对数组
    console.log(Object.entries(school)); // [['name', '尚硅谷'], ['cities', Array(3)], ['xueke', Array(4)]]
    // 创建 Map
    const m = new Map(Object.entries(school)); // {'name' => '尚硅谷', 'cities' => Array(3), 'xueke' => Array(4)}
    console.log(m);
    
  • 返回对象属性的描述对象 Object.getOwnPropertyDescriptors()

    const school = {
      name: "尚硅谷",
      cities: ["北京", "上海", "深圳"],
      xueke: ["前段", "Vue", "Axios", "Java"],
    };
    
    // 对象属性的描述对象
    console.log(Object.getOwnPropertyDescriptors(school));
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值