1. function ajax (url) {
    2. return new Promise(function (resolve, reject) {
    3. let xhr = new XMLHttpRequest()
    4. xhr.open('GET', url)
    5. xhr.responseType = 'json'
    6. xhr.onload = function () {
    7. if (this.status + '' === '200') {
    8. resolve(this.response)
    9. console.log(this.response)
    10. } else {
    11. reject(new Error(this.responseText))
    12. console.log(this.responseText)
    13. }
    14. }
    15. xhr.send()
    16. })
    17. }
    18. function * main () {
    19. try {
    20. const users = yield ajax('/ajaxTest.js')
    21. console.log(users)
    22. const post = yield ajax('/ajaxPost.js')
    23. console.log(post)
    24. }catch (e) {
    25. console.log(e)
    26. }
    27. }
    28. function coo (generator) {
    29. const g = generator()
    30. function handleResult (data) {
    31. if (data.done) return
    32. data.value.then(result => {
    33. handleResult(g.next(data))
    34. }, function (error) {
    35. g.throw(error)
    36. })
    37. }
    38. handleResult(g.next())
    39. }
    40. coo(main)