国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 語(yǔ)言 > JavaScript > 正文

ES7之Async/await的使用詳解

2024-05-06 15:41:16
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

在 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(..),直接可以得到返回值。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 柏乡县| 含山县| 尼玛县| 华坪县| 北碚区| 和龙市| 佳木斯市| 巍山| 崇义县| 卢湾区| 横山县| 乡城县| 积石山| 珲春市| 高密市| 七台河市| 左权县| 乌恰县| 阿瓦提县| 土默特左旗| 荔浦县| 利津县| 增城市| 宁安市| 即墨市| 吉水县| 新疆| 曲阳县| 长顺县| 三明市| 天台县| 内江市| 平武县| 沙湾县| 淮北市| 永胜县| 扎鲁特旗| 杭锦后旗| 宜川县| 炎陵县| 巍山|