JavaScript Async

"async and await make promises easier to write"

async Make the function return Promise

await Make the function wait for Promise

Async syntax

Keyword before the function async Make the function return promise:

Example

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

Equivalent to:

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

The following are methods using Promise:

myFunction().then(
  function(value) { /* Success code */ },
  function(error) { /* Error code */ }
);

Example

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

Kutumia kwenye mazingira

Or even simpler, because you expect a normal value (normal response, not an error):

Example

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

Kutumia kwenye mazingira

Await syntax

Keyword before the function await Make the function wait for promise:

let value = await promise;

await Keywords can only be async Used in function

Example

Let's learn slowly how to use it.

Basic syntax

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

Kutumia kwenye mazingira

Wait for timeout

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

Kutumia kwenye mazingira

Wait for the file

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("File not Found");}
    };
    req.send();
  });
  document.getElementById("demo").innerHTML = await myPromise;
}
getFile();

Kutumia kwenye mazingira

Muafikiano wa kumtandao

ECMAScript 2017 ilianzisha nafasi za nafasi za JavaScript async na await.

Tafanua hili inatoa sababu za programu za kwanza zilizo na husababisha kusaidia mabahari yote

Chrome IE Firefox Safari Opera
Chrome 55 Edge 15 Firefox 52 Safari 11 Opera 42
Desemba 2016 Aprili 2017 Mwaka 2017 hivi karibuni Septemba 2017 Desemba 2016