第八节:ES9之for await of、RegExp扩展、Object扩展、Promise扩展、String扩展

一. for await of

  异步迭代器(for-await-of):循环等待每个Promise对象变为resolved状态才进入下一步

function Gen(time) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve(time)
        }, time)
    })
}

async function test() {
    let arr = [Gen(2000), Gen(100), Gen(3000)]
    for await (let item of arr) {
        console.log(Date.now(), item)
    }
}

test()
// 1560092345730 2000
// 1560092345730 100
// 1560092346336 3000

 

二. RegExp

 doAll模式

 具名组匹配

 后行断言 

 

三. Object扩展

 ES6中 function 有 Rest & Spread 方法,在 ES9 新增 Object 的 Rest & Spread 方法。

1. Spread语法

 可以把 input 对象的数据都拓展到 output 对象, input和output中都有c,则以output中的c为主。

    const input = {
        a: 1,
        b: 2,
        c:5
      }    
      const output = {
        ...input,
        c: 3
      }   
      console.log(output) // {a: 1, b: 2, c: 3}

2. Rest语法

 当对象 key-value 不确定的时候,把必选的 key 赋值给变量,用一个变量收敛其他可选的 key 数据,这在之前是做不到的。

    const input = {
        a: 1,
        b: 2,
        c: 3
      }  
      let { a, ...rest } = input    
      console.log(a)      // 1 
      console.log(rest)  //{b: 2, c: 3}

 

四. Promise扩展

 增加了Promise.prototype.finally():指定不管最后状态如何都会执行的回调函数。

  Promise.prototype.finally() 方法返回一个Promise,在promise执行结束时,无论结果是fulfilled或者是rejected,在执行then()和catch()后,都会执行finally指定的回调函数。这为指定执行完promise后,无论结果是fulfilled还是rejected都需要执行的代码提供了一种方式,避免同样的语句需要在then()和catch()中各写一次的情况。

new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('success')
        // reject('fail')
    }, 1000)
}).then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
}).finally(() => {
    console.log('finally')
})

场景1:loading关闭

  需要每次发送请求,都会有loading提示,请求发送完毕,就需要关闭loading提示框,不然界面就无法被点击。不管请求成功或是失败,这个loading都需要关闭掉,这时把关闭loading的代码写在finally里再合适不过了

场景2:数据库断开链接

let connection
db.open()
    .then(conn => {
        connection = conn
        return connection.select({
            name: 'Jane'
        })
    })
    .then(result => {
        // Process result
        // Use `connection` to make more queries
    })···
    .catch(error => {
        // handle errors
    })
    .finally(() => {
        connection.close()
    })

 

五. String扩展

  ES9 标准移除了对 ECMAScript带标签的模板字符串 中转义序列的语法限制。

    function tag(strs) {
        console.log(strs)
        // strs[0] === undefined
        // strs.raw[0] === "\\unicode and \\u{55}"
    }
    
    // 在标签函数中使用
    tag `\u{61} and \u{62}`  //
    tag `\u{61} and \unicode`  // 结果是 undefined
    
    // 之前的版本会报错:Invalid Unicode escape sequence
    // 无效的Unicode转义序列

 

 

 

 

 

!

  • 作       者 : Yaopengfei(姚鹏飞)
  • 博客地址 : http://www.cnblogs.com/yaopengfei/
  • 声     明1 : 如有错误,欢迎讨论,请勿谩骂^_^。
  • 声     明2 : 原创博客请在转载时保留原文链接或在文章开头加上本人博客地址,否则保留追究法律责任的权利。
 

 

posted @ 2021-04-25 16:58  Yaopengfei  阅读(198)  评论(1编辑  收藏  举报