1. XHR
  2. $.ajax
  3. fetch缺点
    1. 只对网络请求报错,对 400, 500 都当做成功的请求
    2. 默认不会带 cookie
    3. 不支持 abort,不支持超时控制
    4. 没有办法监听请求的进度
  4. axios特点
    1. 浏览器和node 环境都可以使用
    2. 完全支持 promise API
    3. 支持取消请求,JSON数据转换
  5. async & await

Promise深入理解高阶函数
发布订阅模式
观察者模式
Promise核心
Generator和实现CO类库
async & await原理
实现完整的 PromiseA+类库
包含 race, all, finally, try等方法

image.png

XMLHttpRequest

MDN https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest

  1. const xhr = new XMLHttpRequest()
  2. xhr.open('GET', 'http://www.lulongwen.com/api/list')
  3. xhr.responseType = 'json'
  4. xhr.onload = () => {
  5. console.log(xhr.response)
  6. }
  7. xhr.onerror = () => {
  8. console.log('error')
  9. }
  10. xhr.send()

jQuery $.ajax()

  1. const options = {
  2. type: 'POST',
  3. url: 'www.lulongwen.com/api/list',
  4. data: {},
  5. dataType: 'json',
  6. success: () => {}
  7. error: () => {}
  8. }
  9. $.ajax(options)

es6 fetch

  1. window.fetch('/api/list')
  2. .then(res => res.json())
  3. .then(res => { console.log(res) })
  4. .catch(err => {console.log(err)})
  5. .finally(() => this.setState({loading: false}) )

JS异步的发展

callback

  1. 回调函数来处理异步逻辑
    1. 把函数当做参数,传入到函数中,形成一个调用栈,依次执行调用
    2. 缺点:形成箭头代码,层级嵌套太深,形成回调地域
  2. 回调函数的本质:程序栈,stack;先进先出的原则,一次执行回调函数
  3. 箭头代码

箭头代码.jpg
image.png

JQuery

  1. $.ajax()
  2. .done(data => {})
  3. .fail(err => {})
  4. $.get()
  5. $.post()
  6. $.getJSON(url, callback) // JSONP
  7. $.when()
  8. $.Deferred() // 延迟对象

JSONP

  1. JSONP
  2. JSON + padding

Promise

async await

async 函数返回的是一个 Promise 对象
await