概述
    相对于 generator async 最大的好处是不许再去配合一个生成器函数执行器
    async 函数会返回一个promise 对象 更加利于对整体代码的控制
    async中的awit 关键词 只能出现在 async 内部 不能在外部使用

    示例

    1. // Async/Await 语法糖
    2. function ajax(url) {
    3. return new Promise(function (resolve, reject) {
    4. var xhr = new XMLHttpRequest()
    5. xhr.open('GET', url)
    6. // HTML5中引入的新特性 请求完成后直接拿到 json对象
    7. xhr.responseType = 'json';
    8. // HTML5中引入的新特性 请求完成后执行
    9. xhr.onload = function () {
    10. if (this.status === 200) {
    11. resolve(this.response)
    12. } else {
    13. reject(new Error(this.statusText))
    14. }
    15. }
    16. xhr.send();
    17. })
    18. }
    19. // 生成器函数执行器
    20. function co(generator){
    21. const g = generator();
    22. function handleResult(result) {
    23. if (result.done) return // 生成器函数结束
    24. result.value.then(data => {
    25. handleResult(g.next(data))
    26. }, error => {
    27. g.throw(error)
    28. })
    29. }
    30. handleResult(g.next());
    31. }
    32. // 相对于 generator async 最大的好处是不许再去配合一个生成器函数执行器
    33. // async 函数会返回一个promise 对象
    34. // 更加利于对整体代码的控制
    35. // async中的awit 关键词 只能出现在 async 内部 不能在外部使用
    36. async function main() {
    37. try {
    38. const users = await ajax('./api/users.json')
    39. console.log(users);
    40. const posts = await ajax('./api/posts.json')
    41. console.log(posts);
    42. const urls = await ajax('./api/urls111.json')
    43. console.log(urls);
    44. } catch (err) {
    45. console.log("2-17",err);
    46. }
    47. }
    48. // co(main)
    49. main()
    50. Promise.resolve(1).then(2).then(Promise.resolve(3)).then(value=>{console.log(value)})