Javascript Promise - async/await (Examples)

Tech:
Javascript
Since:
2 years ago
Views:
5

In Javascript promises are used to handle asynchronous operations. It is either resolved or rejected based on the result of the asynchronous operation. The async/await syntax is used to handle asynchronous operations.

Async / Await

In promise async/await function will wait until resolve or reject is returned.

var done = true;
const isJobDone = function() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      if (done) {
        resolve("Job  1 done");
      } else {
        reject("Still working 1");
      }
    }, 2000);
  });
};

const check = async function() {
  try {
    var val = await isJobDone();
    // Rest of the code after resolved
    console.log(val);
  } catch (val) {
    console.log(val);
  }
};

check();

Async / Await Channing 1

var done1 = true;
var done2 = true;
const isJobDone1 = function() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      if (done1) {
        resolve("Job 1 done");
      } else {
        reject("Still working 1");
      }
    }, 2000);
  });
};
const isJobDone2 = function() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      if (done2) {
        resolve("Job 2 done");
      } else {
        reject("Still working 2");
      }
    }, 2000);
  });
};
const check = async function() {
  try {
    var val1 = await isJobDone1();
    console.log(val1);
    var val2 = await isJobDone2();
    console.log(val2);
  } catch (val) {
    console.log(val);
  }
};

check();

Async / Await Channing 2

const isJobDone3 = function() {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve("Job 3");
    }, 2000);
  });
};

const isJobDone2 = async function() {
  const val = await isJobDone3();
  return "Job 2 and " + val;
};

const isJobDone1 = async function() {
  const val = await isJobDone2();
  return "Job 1, " + val + " are done";
};

isJobDone1().then(res => {
  console.log(res);
});