iT邦幫忙

0

JS XHR,Fetch,Promise,Async

  • 分享至 

  • xImage
  •  

大綱

  • 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 一建立會自動開始執行 !
  1. pending 剛建立的狀態
  2. resolve 成功後回傳 對應 then
  3. reject 錯誤時回傳 對應 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)
  }

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言