promise中调用ajax
生活随笔
收集整理的這篇文章主要介紹了
promise中调用ajax
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Promise是異步里面的一種解決方案,解決了回調嵌套的問題,es6將其進行了語言標準,同意了用法,提供了`promise`對象,?promise對象有三種狀態:pending(進行中) 、Resolved(已經完成)和Rejected(已失敗)
另外,then方法指定的回調函數,如果運行中拋出錯誤,也會被catch方法捕獲。 如果Promise狀態已經變成Resolved,再拋出錯誤是無效的。 catch方法返回的還是一個Promise對象,因此后面還可以接著調用then方法。
ES6規定,Promise對象是一個構造函數,用來生成Promise實例。
| 1 2 3 4 5 6 7 | var?promise=new?Promise(function(resove,reject){ ?????if?(/* 異步操作成功 */){ ????resolve(value); ??}?else?{ ????reject(error); ??} }) |
Promise實例生成以后,可以用then方法分別指定Resolved狀態和Reject狀態的回調函數。
| 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('我后執行') ?????}) ?????console.log('我先執行')<br><br>//上面代碼中,Promise新建后立即執行,所以首先輸出的是“Promise”。然后,<code>then</code>方法指定的回調函數,<br>//將在當前腳本所有同步任務執行完才會執行,所以“我后執行” 最后輸出。 |
?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三種狀態
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()
鏈式調用,狀態變為resolve
如果把下一步想要的東西return出去,即可讓下一個then使用
上面的代碼還可以借用箭頭函數簡寫成,極大提升了代碼的簡潔性和可讀性
promise.then(res => res.data).then(data => data.result) .then(result => console.log(result));Promise.prototype.catch()
如果異步操作拋出錯誤,狀態就會變為Rejected,就會調用catch方法指定的回調函數,處理這個錯誤。
總結
以上是生活随笔為你收集整理的promise中调用ajax的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 理解Promise规范
- 下一篇: SVM(support vector m