ES2017(ES8)新特性

async和await

async 和 await 两种语法结合可以让异步代码像同步代码一样。

async函数

async 函数的返回值为 Promise 对象,Promise 对象的结果由 async 函数执行的返回值决定。

  • return 的不是一个 Promise 类型的对象, async 函数的返回值就是成功 Promise 对象。
// async 函数
async function fn() {
    // return 的不是一个 Promise 类型的对象, async 函数的返回值就是成功 Promise 对象
    return '尚硅谷'
}

const result = fn()
console.log(result)

// 调用 then 方法
result.then(value => {
    console.log('value:', value)
}, reason => {
    console.warn('reason:', reason)
})

结果:
async函数

  • 抛出错误, async 函数的返回值是一个失败的 Promise 对象。
// async 函数
async function fn() {
    // 抛出错误, async 函数的返回值是一个失败的 Promise 对象
    throw new Error('出错啦!')
}

const result = fn()
console.log(result)

// 调用 then 方法
result.then(value => {
    console.log('value:', value)
}, reason => {
    console.warn('reason:', reason)
})

结果:
async函数

  • 返回的结果如果是一个 Promise 对象。
// async 函数
async function fn() {
    // 返回的结果如果是一个 Promise 对象
    return new Promise((resolve, reject) => {
        resolve('成功的数据')
        reject('失败的数据')
    })
}

const result = fn()
console.log(result)

// 调用 then 方法
result.then(value => {
    console.log('value:', value)
}, reason => {
    console.warn('reason:', reason)
})

结果:
async函数

await表达式

  • await 必须写在 async 函数中
  • await 右侧的表达式一般为 Promise 对象
  • await 返回的是 Promise 成功的值
  • await 的 Promise 失败了, 就会抛出异常, 需要通过 try…catch 捕获处理
// 创建 Promise 对象
const p = new Promise((resolve, reject) => {
    // resolve("用户数据")
    reject("失败啦")
})

// await 要放在 async 函数中
async function main() {
    try {
        let result = await p
        console.log(result) // 用户数据
    } catch (e) {
        console.log(e) // 失败啦
    }
}

// 调用函数
main()
// 结果为:失败啦

async和await结合读取文件

node运行环境:

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

function readWeiXue() {
    return new Promise((resolve, reject) => {
        fs.readFile("./resources/为学.md", (err, data) => {
            // 如果失败
            if (err) reject(err)
            // 如果成功
            resolve(data)
        })
    })
}

function readChaYangShi() {
    return new Promise((resolve, reject) => {
        fs.readFile("./resources/插秧诗.md", (err, data) => {
            // 如果失败
            if (err) reject(err)
            // 如果成功
            resolve(data)
        })
    })
}

function readGuanShu() {
    return new Promise((resolve, reject) => {
        fs.readFile("./resources/观书有感.md", (err, data) => {
            // 如果失败
            if (err) reject(err)
            // 如果成功
            resolve(data)
        })
    })
}

// 声明一个 async 函数
async function main() {
    let weixue = await readWeiXue()
    let chayang = await readChaYangShi()
    let guanshu = await readGuanShu()

    console.log(weixue.toString())
    console.log(chayang.toString())
    console.log(guanshu.toString())
}

main()

async与await封装AJAX请求

// 发送 AJAX 请求, 返回的结果是 Promise 对象
function sendAJAX(url) {
    return new Promise((resolve, reject) => {
        //1. 创建对象
        const x = new XMLHttpRequest()

        //2. 初始化
        x.open('GET', url)

        //3. 发送
        x.send()

        //4. 事件绑定
        x.onreadystatechange = function () {
            if (x.readyState === 4)
                if (x.status >= 200 && x.status < 300) // 如果成功
                    resolve(x.response)
                else                                   // 如果失败
                    reject(x.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)
}

main()

自我总结

感觉await的存在就是为了取代then方法的,因为await能获取Promise对象成功的值,然后可以用try...catch捕获Promise对象失败的值。值得注意的是await必须依赖async函数才能使用,我们通常的做法是用函数封装一个Promise,然后用async函数配合await来调用函数,从而获取Promise对象成功的值。

对象方法的扩展

const school = {
    name: "尚硅谷",
    cities: ['北京', '上海', '深圳'],
    xueke: ['前端', 'Java', '大数据', '运维']
}

//获取对象所有的键
console.log(Object.keys(school))


//获取对象所有的值
console.log(Object.values(school))


//Object.entries()方法返回一个给定对象自身可遍历属性 [key, value] 的数组
//对象转为二维数组
console.log(Object.entries(school))
//创建 Map
const m = new Map(Object.entries(school))
console.log(m)


//返回指定对象所有自身属性的描述对象
console.log(Object.getOwnPropertyDescriptors(school))


const obj = Object.create(null, {
    name: {
        //设置值
        value: '尚硅谷',
        //属性特性
        writable: true,
        configurable: true,
        enumerable: true
    }
})
console.log(obj)

结果:
ES8对象方法的扩展

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值