用promise封裝ajax_JS中promise的基礎用法
阿新 • • 發佈:2021-01-14
技術標籤:用promise封裝ajax
pormise在我看來,主要來優化存在多個ajax請求時,可以把回撥函式給獨立出來,統一呼叫。
比如在以前,我們在進行多個ajax請求時,第二個請求需要用到第一個請求返回的資料時,我們通常是這樣的:
$.ajax({ url: 'xxx.php', method: 'post', data: {page:1}, datatype: 'json', success: (res) => { var id = res.id;//得到請求返回的資料,進行第二次請求 $.ajax({ url: 'xxx.php', method: 'post', data: { id: id }, datatype: 'json', success: (res) => { } }) }, error: (err) => { } });
可能有人優化會對ajax做個函式的封裝,但實際還是巢狀的,promise就能把回撥函式給獨立出來,然後鏈式呼叫。
我們優化一下上面的程式碼:
var promise = new Promise(function (resolve, reject) { $.ajax({ url: '/Dome/Json.ashx', method: 'get', datatype: 'json', success: (res) => { console.log("Json.ashx"); var obj = JSON.parse(res); resolve(obj[1].ID); }, error: (err) => { reject("/Dome/Json.ashx"); } }); }); function handler(data=1) { var promise1 = new Promise(function (resolve, reject) { $.ajax({ url: '/ashx/PageHandler.ashx', method: 'get', data: {page:data}, datatype: 'json', success: (res) => { console.log("PageHandler.ashx"); resolve(res); }, error: (err) => { reject("/ashx/PageHandler.ashx"); } }); }); return promise1; } function failed(url) { console.log(`請求失敗:${url}`); } //呼叫 promise.then(handler, failed).then(function (data) { console.log(data); }, failed)
這裡首先來解釋一下上面的程式碼:
首先例項一個Promise物件,然後有兩個引數,第一個為resolve,第二個為reject,前者一般為成功的時候呼叫,後者是失敗的時候呼叫。
我們主要說呼叫那裡的程式碼,then方法可以把回撥函式分離出來,then函式有兩個引數,均為函式,前者是請求成功的函式,後者是請求失敗的函式。
這裡第一次呼叫then,就執行第一個ajax請求,然後傳入兩個函式,handler和failed,這裡是handler就是上面ajax的第二個請求,由於第一個ajax請求成功,呼叫了resolve函式,promise就會呼叫handler函式,如果請求失敗,則進入reject,那就會呼叫failed函式。
然後還要講的一個函式是promise的all函式。all函式主要用於多個請求的資料無關聯的時候。
上述的程式碼不變,我們把呼叫改一下:
//適用於多個ajax請求,但是每個ajax返回資料無關聯的情況 Promise.all([promise, handler()]).then(function (result) { console.log("結束"); console.log(result); })
all函式會等待全部請求完成之後,才完成回撥,資料則在result中用陣列的形式返回。
陣列中的資料是每個resolve中每個傳入的資料。
promise不止用於非同步請求,很多場景都可以用,需要大家靈活應用。