JS XHR,Fetch,Promise,Async

大纲

xhr 用法fetch 用法Promise 解说xhr + promise 实作async /await with fetch 用法

xhr

onreadystatechange 与 onload 择一
onreadystatechange 需多判断变数
  getData('https://jsonplaceholder.typicode.com/user')  function getData(url) {    const xhr = new XMLHttpRequest()    xhr.open('GET', url, true)    xhr.onload = function () {      if (xhr.status === 200) {        console.table(JSON.parse(this.response))      }    }    xhr.onerror = function () {      console.error(new Error(`连结失败${xhr.status}`))    }    xhr.send(null)  }

fetch

回传 promise 物件
fetch('https://jsonplaceholder.typicode.com/users')  // 必须先将资料转成json格式  .then(res => res.json())  // 取得资料  .then((data) => {    console.table(data)  })

Promise 状态

Promise 一建立会自动开始执行 !pending 刚建立的状态resolve 成功后回传 对应 thenreject 错误时回传 对应 catch

Promise 应用

promise 物件建立promise function 回传 promise 物件then 用法串接 (只要回传结果为promise物件即可用)Promise.all (避免使用,一次性发过多AJAX)一次送出去,需等全部回来才动作,无法控制顺序Promise.race 只看首个完成的 (较少用)
  const p1 = new Promise((resolve, reject) => {    // 条件: 完成 setTimeout 或 API 取得资料    if (true) { resolve('OK')}     else { reject(new Error('ERROR')) }  })
const promiseFunc = function (url) {  return new Promise((resolve, reject) => {    // 条件: 完成 setTimeout 或 API 取得资料    if (true) { resolve('OK')}     else { reject(new Error('ERROR')) }  })}
  promise.then((result) => {    console.log(result)    return someFunc()  }).catch((err) => { console.error(err) })
  Promise.all([funcA(), funcB()])  .then((result) => {    console.log(result)  }).catch((err) => { console.error(err) })

xhr + promise

宣告成 promise 物件将 response 转成物件后,resolve 传至 result
  const test = new Promise((resolve, reject) => {    const xhr = new XMLHttpRequest()    const url = 'https://jsonplaceholder.typicode.com/users'    xhr.open('GET', url, true)    xhr.onload = () => {      if (xhr.status >= 200 && xhr.status < 400) {        console.table(JSON.parse(xhr.response))        resolve(JSON.parse(xhr.response))       } else {        reject(new Error(`连结失败${xhr.status}`))      }    }    xhr.send(null)  })  test.then((result) => {    console.table(result)  }).catch((err) => { console.error(err) })

async / await with fetch

Promise的封装
  run()  async function run() {    const res = await fetch('https://jsonplaceholder.typicode.com/users')    const data = await res.json()    console.table(data)  }

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章