Skip to Main Content
現代JavaScript實務應用
book

現代JavaScript實務應用

by Nicolas Bevacqua
May 2018
Intermediate to advanced content levelIntermediate to advanced
336 pages
5h 16m
Chinese
GoTop Information, Inc.
Content preview from 現代JavaScript實務應用
90
|
第四章 迭代和流程控制
4.1.1 開始學習 Promise
參考以下範例,我們來看看瀏覽器所支援的新的
fetch
API。這個 API
是一個簡化版的
XMLHttpRequest
,旨在提供使用者一個非常簡單的方式
來處理經常使用的案例:也就是以 HTTP 資源發送
GET
請求。它還有提
供了一個延伸的 API 可以滿足進階的使用情境,但這不在我們目前的討
論範圍中。它基本的使用方式,可建立一個
GET
/
items
HTTP 請求,
只要使用如下的程式指令即可達成。
fetch('/items')
只看這個
fetch('
/
items')
敘述句似乎還不過癮,它會對 /
items
建立一
個「開始並遺忘」的
GET
請求,這代表不管所送出的請求是否成功,你
可以忽略回覆並繼續向下執行。
fetch
方法會回傳一個
Promise
物件。
你可以於該
Promise
物件利用
.then
方法鏈結一個回呼函式,當 /
items
資源完成載入並接收到
response
物件,便會執行指定的回呼函式。
fetch('/items').then(response => {
// 執行某些動作
})
以下的程式碼展示以 Promise 為基礎的 API,利用它便可以將
fetch
瀏覽器端完整實際地實作。呼叫
fetch
函式會取得一個
Promise
物件,
就如事件一般,你可以利用
.then
.catch
方法,將該情境下應進行的
動作進行繫結。
const p = fetch('/items')
p.then(res => {
// 處理回應
})
p.catch(err ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

精實企業|高績效組織如何達成創新規模化

精實企業|高績效組織如何達成創新規模化

Jez Humble, Joanne Molesky, Barry O'Reilly
C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
優雅的SciPy|Python科學研究的美學

優雅的SciPy|Python科學研究的美學

Juan Nunez-Iglesias, Stéfan van der Walt, Harriet Dashnow

Publisher Resources

ISBN: 9789864767885