概述
相对于 generator async 最大的好处是不许再去配合一个生成器函数执行器
async 函数会返回一个promise 对象 更加利于对整体代码的控制
async中的awit 关键词 只能出现在 async 内部 不能在外部使用
示例
// Async/Await 语法糖function ajax(url) {return new Promise(function (resolve, reject) {var xhr = new XMLHttpRequest()xhr.open('GET', url)// HTML5中引入的新特性 请求完成后直接拿到 json对象xhr.responseType = 'json';// HTML5中引入的新特性 请求完成后执行xhr.onload = function () {if (this.status === 200) {resolve(this.response)} else {reject(new Error(this.statusText))}}xhr.send();})}// 生成器函数执行器function co(generator){const g = generator();function handleResult(result) {if (result.done) return // 生成器函数结束result.value.then(data => {handleResult(g.next(data))}, error => {g.throw(error)})}handleResult(g.next());}// 相对于 generator async 最大的好处是不许再去配合一个生成器函数执行器// async 函数会返回一个promise 对象// 更加利于对整体代码的控制// async中的awit 关键词 只能出现在 async 内部 不能在外部使用async function main() {try {const users = await ajax('./api/users.json')console.log(users);const posts = await ajax('./api/posts.json')console.log(posts);const urls = await ajax('./api/urls111.json')console.log(urls);} catch (err) {console.log("2-17",err);}}// co(main)main()Promise.resolve(1).then(2).then(Promise.resolve(3)).then(value=>{console.log(value)})
