JavaScript Async

"async and await make promises easier to write"

async 使函数返回 Promise

await 使函数等待 Promise

Async 语法

函数前的关键字 async 使函数返回 promise:

实例

async function myFunction() {
  return "Hello";
}

等同于:

async function myFunction() {
  return Promise.resolve("Hello");
}

以下是使用 Promise 的方法:

myFunction().then(
  function(value) { /* 成功时的代码 */ },
  function(error) { /* 出错时的代码 */ }
);

实例

async function myFunction() {
  return "Hello";
}
myFunction().then(
  function(value) {myDisplayer(value);},
  function(error) {myDisplayer(error);}
);

Experimente por si mesmo

或者更简单,因为您期望正常值(正常响应,而不是错误):

实例

async function myFunction() {
  return "Hello";
}
myFunction().then(
  function(value) {myDisplayer(value);}
);

Experimente por si mesmo

Await 语法

函数前的关键字 await 使函数等待 promise:

let value = await promise;

await 关键字只能在 async 函数中使用。

实例

让我们慢慢来学习如何使用它。

基础语法

async function myDisplay() {
  let myPromise = new Promise(function(myResolve, myReject) {
    myResolve("I love You !!");
  });
  document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();

Experimente por si mesmo

等待超时

async function myDisplay() {
  let myPromise = new Promise(function(myResolve, myReject) {
    setTimeout(function() { myResolve("I love You !!"); }, 3000);
  });
  document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();

Experimente por si mesmo

等待文件

async function getFile() {
  let myPromise = new Promise(function(myResolve, myReject) {
    let req = new XMLHttpRequest();
    req.open('GET', "mycar.html");
    req.onload = function() {
      if (req.status == 200) {myResolve(req.response);}
      else {myResolve("Arquivo Não Encontrado");}
    };
    req.send();
  });
  document.getElementById("demo").innerHTML = await myPromise;
}
getFile();

Experimente por si mesmo

Suporte do Navegador

ECMAScript 2017 introduziu a palavra-chave JavaScript async e await.

A tabela a seguir indica a primeira versão do navegador que suporta ambos:

Chrome IE Firefox Safari Opera
Chrome 55 Edge 15 Firefox 52 Safari 11 Opera 42
Dezembro de 2016 Abril de 2017 Março de 2017 Setembro de 2017 Dezembro de 2016