Fetch & Promise


Posted by chihyu on 2021-01-25

Fetch

  • 在前端網站用 ajax 發 request 的一種方法
    (註:另一種是 XtmlHttpRequest)
  • 非同步(async)

Mocky-生成 api 的工具

開始使用 Fetch

  • 發 request,在 fetch 裡面直接放 url,回傳的 request 是 一個 promise

    Promise
    是一個物件類型,一種獨特的物件

fetch("https://run.mocky.io/v3/9657cc69-c0ee-401b-b85c-c3fbb5cd0444") // 回傳 Promise
  • 拿 promise 的結果用 .then(),裡面要放 function,回傳的是一個 response
    const result = fetch("https://run.mocky.io/v3/9657cc69-c0ee-401b-b85c-c3fbb5cd0444")
    result.then(response => {
      console.log(response)
    }) // 回傳 Response
    
  • 拿到結果後用 .text(),拿到裡面的文字,回傳的是一個 promise
    const result = fetch("https://run.mocky.io/v3/9657cc69-c0ee-401b-b85c-c3fbb5cd0444")
    result.then(response => {
      console.log(response.text())
    }) // 回傳 Promise
    
  • 因為回傳的是一個 Promise,要再拿到結果一樣用 .then()
    const result = fetch("https://run.mocky.io/v3/9657cc69-c0ee-401b-b85c-c3fbb5cd0444")
    result.then(response => {
      response.text().then(text => console.log(text))
    }) // 回傳 object
    
  • 用 .json 將拿到轉成 js 的物件格式的結果,回傳的是一個 promise
    const result = fetch("https://run.mocky.io/v3/9657cc69-c0ee-401b-b85c-c3fbb5cd0444")
    result.then(response => {
      response.json().then(text => {
          console.log(text)
      })
    }) // 回傳 Promise
    
  • .then().then(),在第一個 .then() return 的東西是下一個 .then() 回傳的值
    const result= fetch("https://run.mocky.io/v3/9657cc69-c0ee-401b-b85c-c3fbb5cd0444")
    result.then(response => {
      return response.json()
    }).then(json => {
      console.log(json)
    })
    
    回傳物件類型對照表:
執行 回傳的物件類型
fetch(url) Promise
.then(function) Response
.text() Pormise
.json() Promise
.json().then(function) Promise

GET 與錯誤處理

  • 用 catch 去接 error
    const result = fetch("https://run.mocky.io/v3/9657cc69-c0ee-401b-b85c-c3fbb5cd0444")
    resultError.then(response => {
      return response.json()
    }).then(json => { // 拿到真正的資料
      console.log(json)
    }).catch(err => console.log('error', err))
    

POST

參數:apiUrl、method、body、header

const data = {
    "today":"Monday"
}

fetch(apiUrl, {
    method:'POST',
    body:JSON.stringify(data),
    header:new Headers({
        'Content-Type':'application/json'
    })
    credentials:'include',
    mode:'no-cors'
})
  • Content-Type:告訴 server 如何解析 request
  • credentials:跨來源時,允許帶 cookie
  • no-cors:就算不允許跨來源也傳 response,只是 response 會是空的,就不會跑到 catch

Promise

  • 非同步執行流程語法結構
  • 是一個函式的物件
  • Promise 裡的 callback function 都是非同步
    ### 自己做一個 Promise
  • new Promise 裡面放 function,帶兩個參數 ex. reslove、reject
    第一個參數 resolve:回傳 .then()
    function init(resolve, reject) {
      resolve(3)
    }
    const myPromise = new Promise(init)
    myPromise.then((data) => {
      console.log('data', data)
    }) // 回傳 data 3
    
    第二個參數 reject:回傳 .catch()
    function init(resolve, reject) {
      reject(3)
    }
    const myPromise = new Promise(init)
    myPromise.then((data) => {
      console.log('data', data)
    }).catch(err => {
      console.log('err', err)
    }) // 回傳 err 3
    

async & await

async

  • 把 async 寫在 function 前面,才可以把 await 寫在裡面
  • 作為一個非同步的 function
  • 讓 function 回傳的東西是一個 promise

await

  • 把 await 寫在 fetch 前面,讓 fetch 裡面的東西以同步的方式去跑
  • await 後面接的東西要是 Promise 才有用

#Web #fetch #Promise #Async #Await







Related Posts

7天搞懂JS進階議題: 目錄

7天搞懂JS進階議題: 目錄

網際網路是什麼?

網際網路是什麼?

關於 JavaScript Date - 做一個倒數頁面

關於 JavaScript Date - 做一個倒數頁面


Comments