promise存在的意义分析resolve reject catch
生活随笔
收集整理的這篇文章主要介紹了
promise存在的意义分析resolve reject catch
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
簡(jiǎn)介?
new Promise(function(resolve,reject){});狀態(tài)
- pending: 初始狀態(tài),成功或失敗狀態(tài)。
- fulfilled: 意味著操作成功完成。對(duì)應(yīng)resolve
- rejected: 意味著操作失敗。對(duì)應(yīng)reject
resolve:使用resolve? 狀態(tài)變?yōu)閒ulfilled會(huì)調(diào)用第一個(gè)函數(shù)
var?p =?new?Promise(function?(resolve, reject) {var?timer = setTimeout(function?() {console.log('執(zhí)行操作1');resolve('這是數(shù)據(jù)1');}, 1000);}); p.then(function?(data) {console.log(data);console.log('這是成功操作'); });//執(zhí)行操作1 //VM36:8 這是數(shù)據(jù)1 //VM36:9 這是成功操作reject:使用reject? 會(huì)調(diào)用第二個(gè)的then
var?p =?new?Promise(function?(resolve, reject) {reject('這是數(shù)據(jù)2');????? });p.then(function(data){//狀態(tài)為fulfilled時(shí)執(zhí)行console.log(data);console.log('這是成功操作');},function(reason){?//狀態(tài)為rejected時(shí)執(zhí)行console.log(reason);console.log('這是失敗的操作'); });//這是數(shù)據(jù)2 //VM42:10 這是失敗的操作catch:catch與reject一樣
var?p =?new?Promise(function?(resolve, reject) {reject('這是數(shù)據(jù)2');}); p.then(function(data){console.log(data);console.log('這是成功操作'); }).catch(function(reason){console.log(reason);console.log('這是失敗的操作'); });//VM48:8 這是數(shù)據(jù)2 //VM48:9 這是失敗的操作目的:解決回調(diào)地獄
普通寫法
setTimeout(function?() {console.log('我');setTimeout(function?() {console.log('愛');setTimeout(function?() {console.log('米');setTimeout(function?() {console.log('飯');}, 1000);}, 1000);}, 1000); }, 1000); //3 //VM54:2 我 //VM54:4 愛 //VM54:6 米 //VM54:8 飯promise寫法
function?getStr1() {return?new?Promise(function?(resolve, reject) {setTimeout(function?() {resolve('我');}, 1000);}); } function?getStr2() {return?new?Promise(function?(resolve, reject) {setTimeout(function?() {resolve('愛');}, 1000);}); } function?getStr3() {return?new?Promise(function?(resolve, reject) {setTimeout(function?() {resolve('米');}, 1000);}); } function?getStr4() {return?new?Promise(function?(resolve, reject) {setTimeout(function?() {resolve('飯');}, 1000);}); } getStr1().then(function?(data) {console.log(data);return?getStr2(); }).then(function?(data) {console.log(data);return?getStr3(); }).then(function?(data) {console.log(data);return?getStr4(); }).then(function?(data) {console.log(data); }) //Promise?{<pending>} //VM59:30 我 //VM59:33 愛 //VM59:36 米 //VM59:39 飯?
總結(jié)
以上是生活随笔為你收集整理的promise存在的意义分析resolve reject catch的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 螺蛳粉为什么要配鸭脚?
- 下一篇: Laravel添加验证场景提高针对性质的