欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中的await函數(shù)使用小結(jié)

 更新時(shí)間:2024年01月31日 10:24:27   作者:黃梅之俊雅  
async 函數(shù)是 AsyncFunction 構(gòu)造函數(shù)的實(shí)例,并且其中允許使用 await 關(guān)鍵字,async 和 await 關(guān)鍵字讓我們可以用一種更簡(jiǎn)潔的方式寫出基于 Promise 的異步行為,而無(wú)需刻意地鏈?zhǔn)秸{(diào)用 promise,這篇文章主要介紹了JavaScript中的await,需要的朋友可以參考下

JavaScript中的await

先來(lái)介紹一下async 函數(shù)

async 函數(shù)是使用async關(guān)鍵字聲明的函數(shù)。async 函數(shù)是 AsyncFunction 構(gòu)造函數(shù)的實(shí)例,并且其中允許使用 await 關(guān)鍵字。async 和 await 關(guān)鍵字讓我們可以用一種更簡(jiǎn)潔的方式寫出基于 Promise 的異步行為,而無(wú)需刻意地鏈?zhǔn)秸{(diào)用 promise。

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}
async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // Expected output: "resolved"
}
asyncCall();

async 函數(shù)可能包含 0 個(gè)或者多個(gè) await 表達(dá)式。await 表達(dá)式會(huì)暫停整個(gè) async 函數(shù)的執(zhí)行進(jìn)程并出讓其控制權(quán),只有當(dāng)其等待的基于 promise 的異步操作被兌現(xiàn)或被拒絕之后才會(huì)恢復(fù)進(jìn)程。promise 的解決值會(huì)被當(dāng)作該 await 表達(dá)式的返回值。使用 async/await 關(guān)鍵字就可以在異步代碼中使用普通的 try/catch 代碼塊。

注意: await關(guān)鍵字只在 async 函數(shù)內(nèi)有效。如果你在 async 函數(shù)體之外使用它,就會(huì)拋出語(yǔ)法錯(cuò)誤 SyntaxError 。
備注: async/await的目的為了簡(jiǎn)化使用基于 promise 的 API 時(shí)所需的語(yǔ)法。async/await 的行為就好像搭配使用了生成器和 promise。

await概念

await 操作符用于等待一個(gè) Promise 兌現(xiàn)并獲取它兌現(xiàn)之后的值。它只能在異步函數(shù)或者模塊頂層中使用。

await expression;

expression為要等待的 Promise 實(shí)例,Thenable 對(duì)象,或任意類型的值。

返回值:返回從 Promise 實(shí)例或 thenable 對(duì)象取得的處理結(jié)果。如果等待的值不符合 thenable,則返回表達(dá)式本身的值

異常:拒絕(reject)的原因會(huì)被作為異常拋出。

await 通常用于拆開(kāi) promise 的包裝,使用方法是傳遞一個(gè) Promise 作為 expression。使用 await 總會(huì)暫停當(dāng)前異步函數(shù)的執(zhí)行,在該 Promise 敲定(settled,指兌現(xiàn)或拒絕)后繼續(xù)執(zhí)行。函數(shù)的執(zhí)行恢復(fù)(resume)時(shí),await 表達(dá)式的值已經(jīng)變成了 Promise 兌現(xiàn)的值。

若該 Promise 被拒絕(rejected),await 表達(dá)式會(huì)把拒絕的原因(reason)拋出。當(dāng)前函數(shù)(await 所在的函數(shù))會(huì)出現(xiàn)在拋出的錯(cuò)誤的棧追蹤(stack trace),否則當(dāng)前函數(shù)就不會(huì)在棧追蹤出現(xiàn)。

await 總會(huì)同步地對(duì)表達(dá)式求值并處理,處理的行為與 Promise.resolve() 一致,不屬于原生 Promise 的值全都會(huì)被隱式地轉(zhuǎn)換為 Promise 實(shí)例后等待。處理的規(guī)則為,若表達(dá)式:

  • 是一個(gè)原生 Promise(原生Promise 的實(shí)例或其派生類的實(shí)例,且滿足 expression.constructor ===
  • Promise),會(huì)被直接用于等待,等待由原生代碼實(shí)現(xiàn),該對(duì)象的 then() 不會(huì)被調(diào)用。
  • 是 thenable 對(duì)象(包括非原生的 Promise 實(shí)例、polyfill、Proxy、派生類等),會(huì)構(gòu)造一個(gè)新 Promise用于等待,構(gòu)造時(shí)會(huì)調(diào)用該對(duì)象的 then() 方法。
  • 不是 thenable 對(duì)象,會(huì)被包裝進(jìn)一個(gè)已兌現(xiàn)的 Promise 用于等待,其結(jié)果就是表達(dá)式的值。

等待 Promise 的兌現(xiàn)

當(dāng)一個(gè) Promise 被傳遞給 await 操作符,await 將等待該 Promise 兌現(xiàn),并在兌現(xiàn)后返回該 Promise 兌現(xiàn)的值。

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}
async function f1() {
  let x = await resolveAfter2Seconds(10);
  console.log(x); // 10
}
f1();

轉(zhuǎn)換為 promise

若表達(dá)式的值不是 Promise,await 會(huì)把該值轉(zhuǎn)換為已兌現(xiàn)的 Promise,然后返回其結(jié)果。

async function f3() {
  const y = await 20;
  console.log(y); // 20
  const obj = {};
  console.log((await obj) === obj); // true
}
f3();

promise 被拒絕

如果 Promise 被拒絕,則拋出拒絕的原因。

async function f4() {
  try {
    const z = await Promise.reject(30);
  } catch (e) {
    console.error(e); // 30
  }
}
f4();

處理被拒絕的 promise

你可以鏈?zhǔn)秸{(diào)用 catch()(而不是使用 try)以在等待 promise 兌現(xiàn)之前處理被拒絕的 promise。

const response = await promisedFunction().catch((err) => {
  console.error(err);
  return "default response";
});
// response will be "default response" if the promise is rejected

到此這篇關(guān)于JavaScript中的await的文章就介紹到這了,更多相關(guān)JavaScript await內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論