iT邦幫忙

2021 iThome 鐵人賽

DAY 12
1
Modern Web

白話JavaScript系列 第 12

Day12-救世主Promise

  • 分享至 

  • xImage
  •  

前言

在ES6之前,要使用非同步並且正確輸出資料必須透過callback,然而callback不好學習與麻煩,甚至還會有不經意的callback hell,讓開發不舒服。

於是Promise的出現,更直覺的方式解救了蒼生!!!

來學習Promise!!!

docs

promise需要帶入兩個參數,通常會被定義為resolve和reject

promise有三種狀態,當promise動作開始會進入pending,完成時會執行reject或fulfill

  • pending:
  • fulfill
  • reject
const promise = new Promise(function(resolve, reject){
  let result = false
  setTimeout(() => {
    result = true
    if(result){
    resolve('OK status 200')
  }   
    reject('error status 500')
  },1000)
})

然後我們會使用到.then .catch去接受promise的回傳值

  • 當回傳false即會被catch抓住回報錯誤
  • 而正確即被then繼續串接
.then((res) => console.log(res))
.catch((error) => console.log(error))

最後再使用一定會執行的函式finally,結束動作

.then((res) => console.log(res))
.catch((error) => console.log(error))
.finally(() => console.log('end'))

完整程式碼

const promise = new Promise(function(resolve, reject){
  let result = false
  setTimeout(() => {
    result = true
    if(result){
    resolve('OK status 200')
  }   
    reject('error status 500')
  },1000)
})
.then((res) => console.log(res))
.catch((error) => console.log(error))
.finally(() => console.log('end'))

/*
OK status 200
end
*/

補充說明: .then可以一值串接,就跟callback一樣

Promise.all

all method需要等Promise都完成,才會繼續執行

const promise1 = new Promise(function(resolve, reject){
  let result = false
  setTimeout(() => {
    result = true
    if(result){
    resolve('OK status 200')
  }   
    reject('error status 500')
  },1000)
})
const promise2 = new Promise(function(resolve, reject){
  let result = false
  setTimeout(() => {
    result = true
    if(result){
    resolve('OK status 200')
  }   
    reject('error status 500')
  },3000)
})
const promiseAll = Promise.all([promise1,promise2])
.then((res) => console.log(res))
//[ 'OK status 200', 'OK status 200' ]

若我們把其中一個改成false

const promise1 = new Promise(function(resolve, reject){
  let result = false
  setTimeout(() => {
    result = true
    if(result){
    resolve('OK status 200')
  }   
    reject('error status 500')
  },1000)
})
const promise2 = new Promise(function(resolve, reject){
  let result = false
  setTimeout(() => {
    result = false
    if(result){
    resolve('OK status 200')
  }   
    reject('error status 500')
  },3000)
})
const promiseAll = Promise.all([promise1,promise2])
.then((res) => console.log(res))
.catch((error) => console.log('error')) //error

就會被catch抓住!!!


上一篇
Day11-同步&&非同步
下一篇
Day13-Async && Await
系列文
白話JavaScript28
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言