promise 的基本使用
promise
狀態 pending 變成 resolved success 、 rejected fail
只有這兩種狀態 每個promise對象只能改變一次 成功的結果一般稱為 value 失敗稱為reason
promise 的基本使用
`
1.創建promise函數
let p = new Promise((resolve, reject) => {
// 2.執行異步操作的任務
setTimeout(() => {
const time = Date.now()
if (time % 2 == 0) {
resolve('成功了')
} else {
reject('失敗了')
}
}, 500);
//3.1 如果成功 resolve(value)
//3.2 如果失敗 執行 reject(reason)
})
p.then(value => {
//成功得到value onResolved
console.log('success', value)
}, reason => {
//失敗得到reason onRejected
console.log('fail', reason)
})
// 回調地獄 回調函數的嵌套調用 外部回調函數異步執行的結果是嵌套的回調函數執行的條件
dosomething(function(result){
dosomethingElse(result,function(newResult){
doThirdThing(newResult,function(finalResult){
console.log('go to third'+finalResult)
},failCallback)
},failCallback)
},failCallback)
** promise 指定回調函數的方式更加靈活,支持鏈式調用,可以解決回調地獄問題 回調函數的方法必須在在使用前就要調用 不方便處理錯誤 promise 則是異步調用 **
//解決方法 promise 的鏈式調用
dosomething().then((result)=>{
return dosomethingElse(result)
}).then((newResult)=>{
return doThirdThing(newResult)
}).then((finalResult)=>{
console.log('go to third'+finalResult)
}).catch(failCallback)
//終極解決方法 async await
async function request(){
try{
const result=await dosomething(result);
const newResult=await dosomethingElse(newResult);
const finalResult=await doThirdThing(newResult);
console.log('go to third'+finalResult)
}catch(e){
failCallback(e)
}
}
終極解決方法 async await
async function request(){
try{
const result=await dosomething(result);
const newResult=await dosomethingElse(newResult);
const finalResult=await doThirdThing(newResult);
console.log('go to third'+finalResult)
}catch(e){
failCallback(e)
}
}
`