Async / Await 的使用
把异步操作包装成Promise
使用Async / Await
async函数返回一个promise对象
// 把异步操作包装成Promisefunction ajax (url) {return new Promise((resolve, reject) => {var xhr = new XMLHttpRequest()xhr.open('GET', url)xhr.responseType = 'json'xhr.onload = () => {if (xhr.status === 200) {resolve(xhr.response)} else {reject(new Error(xhr.statusText))}}xhr.send()})}// 使用Async / Awaitasync 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/urls.json')console.log(urls)} catch (e) {console.log(e)}}const promise = main()promise.then(() => {console.log('all completed')})
Async / Await的原理
Async / Await就是generator+promise+co函数的语法糖
把generator函数的*替换为async
把generator函数的yeild替换为await
generator+promise+co
Async就相当于把多个异步操作包装成一个promise对象
Await就相当于是内部异步操作的promise.then()的语法糖
// 把异步操作包装成Promisefunction ajax (url) {return new Promise((resolve, reject) => {var xhr = new XMLHttpRequest()xhr.open('GET', url)xhr.responseType = 'json'xhr.onload = () => {if (xhr.status === 200) {resolve(xhr.response)} else {reject(new Error(xhr.statusText))}}xhr.send()})}// Generator 配合 Promise的异步解决方案function * main () {try {const users = yield ajax('/api/users.json')console.log(users)const posts = yield ajax('/api/posts.json')console.log(posts)const urls = yield ajax('/api/urls11.json')console.log(urls)} catch (e) {console.log(e)}}// 解决方案的使用方式// const g = generator()// const result = g.next()// result.value.then(data => {// const result2 = g.next(data)// if (result2.done) return// result2.value.then(data => {// const result3 = g.next(data)// if (result3.done) return// result3.value.then(data => {// g.next(data)// })// })// })// 解决方案的使用方式优化:递归调用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())}// 使用co优化后的使用方式co(main)
