⑥ ES8 异步编程&对象拓展

1 异步编程解决方案 Async Await

async 让我们写起 Promise 像同步操作

  • async/await 是函数定义的关键字

  • await 用于等待 promise 对象的返回结果,且不能单独使用必须放在 async 函数中

  • 利用 async 定义的函数会返回一个 promise 对象

  • async 函数的返回值就是 promise 状态为 resolved 的返回值

1.1 async

  • async 的函数在执行后都会自动返回一个 Promise 对象
function foo() {
  return 'imooc'
}
console.log(foo());

async function foo() {
  return 'imooc' // Promise.resolve('imooc')
}
console.log(foo()); // Promise {<fulfilled>: 'imooc'}

1.2 await

  • await 后面需要跟异步操作,用于等待 Promise 对象的返回结果
function timeout() {
  return new Promise(resolve => {
    setTimeout(() => {
      // console.log(1);
      resolve(1)
    }, 1000);
  })
}
async function foo() {
  const res = await timeout()
  console.log(res);
  console.log(2);
}
foo() // 无await 2 1
foo() // +await 1 2

1.3 错误处理

function timeout() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // resolve('success')
      reject('error')
    }, 1000)
  })
}
async function foo() {
  return await timeout()
}
foo().then(res => {
  console.log(res)
}).catch(err => {
  console.log(err)
})

1.4 应用

  • 需要发送多个请求,而后面请求的发送总是需要依赖上一个请求返回的数据

使用 async/await 按顺序请求文件

import ajax from './ajax'

function request(url) {
  return new Promise(resolve => {
    ajax(url, res => {
      resolve(res)
    })
  })
}
async function getData() {
  const res1 = await request('static/a.json')
  console.log(res1);
  const res2 = await request('static/b.json')
  console.log(res2);
  const res3 = await request('static/c.json')
  console.log(res3);
}
getData()

2 对象扩展:Object.values(),Object.entries()

const obj = {
  name: 'imooc',
  web: 'www.imooc.com',
  course: 'es'
}
  • 如何获取对象的每一个属性值
console.log(Object.keys(obj));
const res = Object.keys(obj).map(key => obj[key])
console.log(res);

2.1 Object.values()

  • 返回一个数组,其元素是在对象上找到的可枚举属性值

2.2 Object.entries()

  • 返回一个给定对象自身可枚举属性的键值对数组

  • 区别于 for-in 循环也枚举原型链中的属性

for(let [key, val] of Object.entries(obj)) {
  console.log(`${key}: ${val}`);
}

console.log(Object.entries(['a', 'b', 'c']));
// [['0', 'a'], ['1', 'b'], ['2', 'c']]

3 对象属性描述:Object.getOwnPropertyDescriptors()

3.1 对象属性

  • value

  • writable 能否改写

  • configurable 能否被删除

  • enumerable 当前属性能否被循环遍历

3.2 获取对象指定属性的描述符

const obj = {
  name: 'imooc',
  course: 'es'
}
const desc = Object.getOwnPropertyDescriptors(obj)
console.log(desc);
// { course: { configurable: true, enumerable: true, value: "es", writable: true }, name: { configurable: true, enumerable: true, value: "imooc", writable: true }}

3.3 设置对象属性

const obj = {}
Reflect.defineProperty(obj, 'name', {
  value: 'zouzou',
  writable: false, // 能否改写
  configurable: false, // 能否被删除
  enumerable: true // 当前属性能否被循环遍历
})
Reflect.defineProperty(obj, 'age', {
  value: '12',
  writable: false,
  configurable: false,
  enumerable: false
})
obj.name = 'zhangsan'
delete obj.name
for(let key in obj) {
  console.log(key);
}

const desc = Object.getOwnPropertyDescriptors(obj)
const desc1 = Object.getOwnPropertyDescriptor(obj, 'age')
console.log(desc);

4 字符串扩展:String.prototype.padStart(),String.prototype.padEnd()

  • 语法:str.padStart(targetLength [, padString])

    • targetLength 目标字符要保持的长度值

    • padString 如果目标字符的长度不够需要的补白字符,默认为空

  • 把指定字符串填充到字符串头部,返回新字符串

const str = 'imooc'
console.log(str.padStart(8, 'xxx')); // xxximooc
console.log(str.padEnd(8, 'xxx')); // imoocxxx
console.log(str.padStart(8)); //  `   imooc`

1. 日期格式化

  • yyyy-mm-dd
const now = new Date()
const year = now.getFullYear()
const month = (now.getMonth() + 1).toString().padStart(2, '0')
const day = (now.getDate()).toString().padStart(2, '0')
console.log(`${year}-${month}-${day}`); // 2022-04-24

2. 数字替换

const tel = '13590098622'
const newTel = tel.slice(-4).padStart(tel.length, '*') // *******8622
console.log(newTel);

5 尾逗号 Trailing commas

  • 允许函数的最后一个参数有尾逗号
function foo(
  a,
  b,
  c,
) {
  console.log(a, b, c);
}
foo(1, 2, 3,)
posted on 2022-05-18 17:30  pleaseAnswer  阅读(27)  评论(0编辑  收藏  举报