當前位置:
首頁 > 知識 > ES6 async 函數

ES6 async 函數

async

async 是 ES7 才有的與非同步操作有關的關鍵字,和 Promise , Generator 有很大關聯的。

語法

async function name([param[, param[, ... param]]]) { statements }

  • name: 函數名稱。
  • param: 要傳遞給函數的參數的名稱。
  • statements: 函數體語句。

返回值

async 函數返回一個 Promise 對象,可以使用 then 方法添加回調函數。

async function helloAsync(){

return "helloAsync";

}

console.log(helloAsync()) // Promise {<resolved>: "helloAsync"}

helloAsync().then(v=>{

console.log(v); // helloAsync

})

async 函數中可能會有 await 表達式,async 函數執行時,如果遇到 await 就會先暫停執行 ,等到觸發的非同步操作完成後,恢復 async 函數的執行並返回解析值。

await 關鍵字僅在 async function 中有效。如果在 async function 函數體外使用 await ,你只會得到一個語法錯誤。

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 操作符用於等待一個 Promise 對象, 它只能在非同步函數 async function 內部使用。

語法

[return_value] = await expression;

  • expression: 一個 Promise 對象或者任何要等待的值。

返回值

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

如果一個 Promise 被傳遞給一個 await 操作符,await 將等待 Promise 正常處理完成並返回其處理結果。

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 命令後面是一個 Promise 對象,它也可以跟其他值,如字元串,布爾值,數值以及普通函數。

function testAwait(){

console.log("testAwait");

}

async function helloAsync(){

await testAwait();

console.log("helloAsync");

}

helloAsync();

// testAwait

// helloAsync

await針對所跟不同表達式的處理方式:

  • Promise 對象:await 會暫停執行,等待 Promise 對象 resolve,然後恢復 async 函數的執行並返回解析值。
  • 非 Promise 對象:直接返回對應的值。

ES6 async 函數

打開今日頭條,查看更多圖片

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

基於ng-zorro的ASP.NET ZERO前端實現
spring mvc 中對靜態資源的訪問配置

TAG:程序員小新人學習 |