日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
講解一下ES6async關(guān)鍵字的使用方法

async 作為一個(gè)關(guān)鍵字放到函數(shù)前面,用于表示函數(shù)是一個(gè)異步函數(shù),因?yàn)閍sync就是異步的意思, 異步函數(shù)也就意味著該函數(shù)的執(zhí)行不會阻塞后面代碼的執(zhí)行。

async

語法

async function name([param[, param[, ... param]]]) { statements }
  1. name: 函數(shù)名稱。
  2. param: 要傳遞給函數(shù)的參數(shù)的名稱。
  3. statements: 函數(shù)體語句。

返回值

async 函數(shù)返回一個(gè) Promise 對象,可以使用 then 方法添加回調(diào)函數(shù)。

async function helloAsync(){
   return "helloAsync";
 }
 
console.log(helloAsync())  // Promise {: "helloAsync"}

helloAsync().then(v=>{
  console.log(v);         // helloAsync
})

async 函數(shù)中可能會有 await 表達(dá)式,async 函數(shù)執(zhí)行時(shí),如果遇到 await 就會先暫停執(zhí)行 ,等到觸發(fā)的異步操作完成后,恢復(fù) async 函數(shù)的執(zhí)行并返回解析值。

await 關(guān)鍵字僅在 async function 中有效。如果在 async function 函數(shù)體外使用 await ,你只會得到一個(gè)語法錯誤。

function testAwait(){
  return new Promise((resolve) => {
      setTimeout(function(){
         console.log("testAwait");
         resolve();
      }, 1000);
  });
}

async function helloAsync(){
  await testAwait();
  console.log("helloAsync");
}
helloAsync();
// testAwait
// helloAsync

await

await 操作符用于等待一個(gè) Promise 對象, 它只能在異步函數(shù) async function 內(nèi)部使用。

語法

[return_value] = await expression;

expression: 一個(gè) Promise 對象或者任何要等待的值。

返回值

返回 Promise 對象的處理結(jié)果。如果等待的不是 Promise 對象,則返回該值本身。

如果一個(gè) Promise 被傳遞給一個(gè) await 操作符,await 將等待 Promise 正常處理完成并返回其處理結(jié)果。

function testAwait (x) {
 return new Promise(resolve => {
   setTimeout(() => {
     resolve(x);
   }, 2000);
 });
}

async function helloAsync() {
 var x = await testAwait ("hello world");
 console.log(x);
}
helloAsync ();
// hello world

正常情況下,await 命令后面是一個(gè) Promise 對象,它也可以跟其他值,如字符串,布爾值,數(shù)值以及普通函數(shù)。

function testAwait(){
  console.log("testAwait");
}
async function helloAsync(){
  await testAwait();
  console.log("helloAsync");
}
helloAsync();
// testAwait
// helloAsync

await針對所跟不同表達(dá)式的處理方式:

Promise 對象:await 會暫停執(zhí)行,等待 Promise 對象 resolve,然后恢復(fù) async 函數(shù)的執(zhí)行并返回解析值。 非 Promise 對象:直接返回對應(yīng)的值。


網(wǎng)頁名稱:講解一下ES6async關(guān)鍵字的使用方法
URL地址:http://www.5511xx.com/article/ccogocp.html