Thursday, 5 November 2020

Javascript Promise, async function and await

  In fact the return value of an async function is a promise.

Promise :

var myPromise = new Promise(
    function (resolve,reject) {
      var x = MyDataStore(myObj);
      resolve(x);
    });

myPromise.then(
  function (x) {
    init(x);
});

Async function :
async function f() {
  return 1;
}
async function f() {
  return 1;
}

f().then(alert); // 1

Async && Await
await can only be used in async
its awaiting for promises in async function to finish instead of continue executing with call back
async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  alert(result); // "done!"
}

f();
// My function
const myfunction = async function(x, y) {
  return [
    x,
    y,
  ];
}

// Start function
const start = async function(a, b) {
  const result = await myfunction('test', 'test');
  
  console.log(result);
}

// Call start
start();
https://javascript.info/async-await
https://stackoverflow.com/questions/34401389/what-is-the-difference-between-javascript-promises-and-async-await
https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function





No comments:

Post a Comment