在 js 異步請(qǐng)求數(shù)據(jù)時(shí),通常,我們多采用回調(diào)函數(shù)的方式解決,但是,如果有多個(gè)回調(diào)函數(shù)嵌套時(shí),代碼顯得很不優(yōu)雅,維護(hù)成本也相應(yīng)較高。 ES6 提供的 Promise 方法和 ES7 提供的 Async/Await 語(yǔ)法糖可以更好解決多層回調(diào)問(wèn)題。
Promise 對(duì)象用于表示一個(gè)異步操作的最終狀態(tài)(完成或失敗),以及其返回的值。
await 操作符用于等待一個(gè)Promise 對(duì)象。它只能在異步函數(shù) async function 中使用。
await 表達(dá)式會(huì)暫停當(dāng)前 async function 的執(zhí)行,等待 Promise 處理完成。若 Promise 正常處理(fulfilled),其回調(diào)的resolve函數(shù)參數(shù)作為 await 表達(dá)式的值,繼續(xù)執(zhí)行 async function。
一個(gè)ajax請(qǐng)求時(shí)
通常 使用 ajax 請(qǐng)求數(shù)據(jù)時(shí),會(huì)
$.ajax({ url: 'data1.json', type: 'GET', success: function (res) { console.log(res) // 請(qǐng)求成功,則得到結(jié)果res }, error: function(err) { console.log(err) }})上面可以得到我們想要的結(jié)果 res ---> { "url": "data2.json" }
多個(gè)ajax請(qǐng)求時(shí)
但是 當(dāng)?shù)玫降臄?shù)據(jù) res 需要用于另一個(gè) ajax 請(qǐng)求時(shí),則需要如下寫法:
$.ajax({ url: 'data1.json', type: 'GET', success: function (res) { $.ajax({ url: res.url, // 將 第一個(gè)ajax請(qǐng)求成功得到的res 用于第二個(gè)ajax請(qǐng)求 type: 'GET', success: function (res) { $.ajax({ url: res.url, // 將第二個(gè)ajax請(qǐng)求成功得到的res 用于第三個(gè)ajax請(qǐng)求 type: 'GET', success: function (res) { console.log(res) // {url: "this is data3.json"} }, error: function(err) { console.log(err) } }) }, error: function(err) { console.log(err) } }) }, error: function(err) { console.log(err) }})上面出現(xiàn)多個(gè)回調(diào)函數(shù)的嵌套,可讀性較差(雖然這種嵌套在平常的開發(fā)中少見,但是在node服務(wù)端開發(fā)時(shí),還是很常見的)
優(yōu)化方法
使用 promise 鏈?zhǔn)讲僮?/p>
如下,使用 Promise,進(jìn)行鏈?zhǔn)讲僮鳎梢允股厦娴漠惒酱a看起來(lái)如同步般易讀,從回調(diào)地獄中解脫出來(lái)。。
function ajaxGet (url) { return new Promise(function (resolve, reject) { $.ajax({ url: url, type: 'GET', success: function (res) { resolve(res); }, error: function(err) { reject('請(qǐng)求失敗'); } }) })};ajaxGet('data1.json').then((d) => { console.log(d); // {url: "data2.json"} return ajaxGet(d.url);}).then((d) => { console.log(d); // {url: "data3.json"} return ajaxGet(d.url);}).then((d) => { console.log(d); // {url: "this is data3.json"}})Async/await 方法
async 表示這是一個(gè)async函數(shù),即異步函數(shù),await只能用在這個(gè)函數(shù)里面。 await 表示在這里等待promise返回結(jié)果了,再繼續(xù)執(zhí)行。 await 后面跟著的應(yīng)該是一個(gè)promise對(duì)象(當(dāng)然,其他返回值也沒(méi)關(guān)系,只是會(huì)立即執(zhí)行,不過(guò)那樣就沒(méi)有意義了…) await 操作符用于等待一個(gè)Promise 對(duì)象。它只能在異步函數(shù) async function 中使用。 await 等待的雖然是promise對(duì)象,但不必寫.then(..),直接可以得到返回值。新聞熱點(diǎn)
疑難解答
圖片精選