在ES6之前,要使用非同步並且正確輸出資料必須透過callback,然而callback不好學習與麻煩,甚至還會有不經意的callback hell,讓開發不舒服。
於是Promise的出現,更直覺的方式解救了蒼生!!!
來學習Promise!!!
promise需要帶入兩個參數,通常會被定義為resolve和reject
promise有三種狀態,當promise動作開始會進入pending,完成時會執行reject或fulfill
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的回傳值
.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一樣
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抓住!!!