promise中调用ajax
生活随笔
收集整理的這篇文章主要介紹了
promise中调用ajax
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Promise是異步里面的一種解決方案,解決了回調(diào)嵌套的問題,es6將其進行了語言標(biāo)準(zhǔn),同意了用法,提供了`promise`對象,?promise對象有三種狀態(tài):pending(進行中) 、Resolved(已經(jīng)完成)和Rejected(已失敗)
另外,then方法指定的回調(diào)函數(shù),如果運行中拋出錯誤,也會被catch方法捕獲。 如果Promise狀態(tài)已經(jīng)變成Resolved,再拋出錯誤是無效的。 catch方法返回的還是一個Promise對象,因此后面還可以接著調(diào)用then方法。
ES6規(guī)定,Promise對象是一個構(gòu)造函數(shù),用來生成Promise實例。
| 1 2 3 4 5 6 7 | var?promise=new?Promise(function(resove,reject){ ?????if?(/* 異步操作成功 */){ ????resolve(value); ??}?else?{ ????reject(error); ??} }) |
Promise實例生成以后,可以用then方法分別指定Resolved狀態(tài)和Reject狀態(tài)的回調(diào)函數(shù)。
| 1 2 3 4 5 | promise.then(function(value) { ??// success },?function(error) { ??// failure }); |
案例
| 1 2 3 4 5 6 7 | var?promise=new?Promise(function(resolve,reject){ ?????????console.log('promise'); ?????}) ?????promise.then(function(){ ????????console.log('我后執(zhí)行') ?????}) ?????console.log('我先執(zhí)行')<br><br>//上面代碼中,Promise新建后立即執(zhí)行,所以首先輸出的是“Promise”。然后,<code>then</code>方法指定的回調(diào)函數(shù),<br>//將在當(dāng)前腳本所有同步任務(wù)執(zhí)行完才會執(zhí)行,所以“我后執(zhí)行” 最后輸出。 |
?ajax
var?http = { ????get:?function(url) { ????????var?promise =?new?Promise(function(resolve, reject) { ????????????$.ajax({ ????????????????url: url, ????????????????method:?'get', ????????????????success:?function(data) { ????????????????????resolve(data); ????????????????}, ????????????????error:?function(xhr, statusText) { ????????????????????reject(statusText); ????????????????} ????????????}); ????????}); ????????return?promise; ????} }; http.get('solve.php').then(function(data) { ????return?data; },?function(err) { ????return?Promise.reject('Sorry, file not Found.'); }).then(function(data) { ????document.write(data); },?function(err) { ????document.write(err); });Promise三種狀態(tài)
pending、resolved、rejected
使用語法
var promis = new Promise(function(resolve,reject){ $.ajax({ url:'/api/something.json', method:'get', datatype:'json', success:(res) =>{ resolve(res) }, error:(err)=>{ reject(err) } }) }) promis.then(function(res){ console.log(res) }).catch(function(err){ console.log(err) });Promise.prototype.then()
鏈?zhǔn)秸{(diào)用,狀態(tài)變?yōu)閞esolve
如果把下一步想要的東西return出去,即可讓下一個then使用
上面的代碼還可以借用箭頭函數(shù)簡寫成,極大提升了代碼的簡潔性和可讀性
promise.then(res => res.data).then(data => data.result) .then(result => console.log(result));Promise.prototype.catch()
如果異步操作拋出錯誤,狀態(tài)就會變?yōu)镽ejected,就會調(diào)用catch方法指定的回調(diào)函數(shù),處理這個錯誤。
總結(jié)
以上是生活随笔為你收集整理的promise中调用ajax的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 理解Promise规范
- 下一篇: SVM(support vector m