1. 程式人生 > 實用技巧 >ES-ES6:5.3 ES6 async 函式

ES-ES6:5.3 ES6 async 函式

ylbtech-ES-ES6:5.3 ES6 async 函式

1.返回頂部
1、

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 物件:直接返回對應的值。
2、
2.返回頂部
3.返回頂部
4.返回頂部
5.返回頂部
1、 https://www.runoob.com/w3cnote/es6-async.html 2、
6.返回頂部
作者:ylbtech
出處:http://ylbtech.cnblogs.com/
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。