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實務應用
4.1 Promise
|
95
Promise
.resolve(2)
.then(x => x * 7)
.then(x => x - 3)
.then(x => console.log(x))
// <- 11
一個回應也會回傳一個 Promise 物件,對比上一個範例程式,下面的程
式碼等待呼叫第一個
.then
所回傳的物件,須至它的回應已實現後,才
能夠取得;因為
setTimeout
的函式呼叫,大約需要兩秒鐘後才會確認為
已實現的狀態。
Promise
.resolve(2)
.then(x => new Promise(function (resolve) {
setTimeout(() => resolve(x * 1000), x * 1000)
}))
.then(x => console.log(x))
// <- 2000
一個回應也可能以
throw
拋出錯誤,它會使
.then
所回傳的 Promise
件成為已拒絕狀態,並接著進入
.catch
的分支區塊,以 error 物件作為
拒絕的原因。以下程式範例展示如何於
fetch
操作加上一個已實現的回
應;當
fetch
為已實現狀態時,在回應中會拋出一個錯誤,並產生一個
已拒絕的回應,繫結於執行
.then
後所回傳的 Promise 物件上。
const p = fetch('/items')
.then(res => { throw new Error('unexpectedly') })
.catch(err => console.error(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