Saturday, May 4, 2019

async await vs promises

In this post, we will understand the difference between async await vs promises. async/await is a special syntax to work with promises in a more comfortable fashion, called “async/await”. It’s surprisingly easy to understand and use.

Async/await in Javascript

Async/await is a new way to write asynchronous code. It is built on top of promises, therefore, it is also non-blocking.
The big difference is that asynchronous code looks and behaves a little more like synchronous code. This is where all its power lies.
The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions:
function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
    }, 2000);

async function asyncCall() {
  var result = await resolveAfter2Seconds();
  // expected output: 'resolved'

Asynchronous functions can be paused with await, the keyword that can only be used inside an async function. Await returns whatever the async function returns when it is done.

Promises in Javascript

Promises In Javascript

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

A promise is an object that may produce a single value some time in the future: either a resolved value or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending.

Fulfilled: onFulfilled() will be called (e.g., resolve() was called)
Rejected: onRejected() will be called (e.g., reject() was called)
Pending: not yet fulfilled or rejected

Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

Promises following the spec must follow a specific set of rules:
A promise or “thenable” is an object that supplies a standard-compliant .then() method.
A pending promise may transition into a fulfilled or rejected state.
A fulfilled or rejected promise is settled, and must not transition into any other state.
Once a promise is settled, it must have a value (which may be undefined). That value must not change.

let promise = new Promise(function(resolve, reject) {
  // some stuff

Promise Code Example:
var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
  }, 300);
promise1.then(function(value) {
  // expected output: "foo"

// expected output: [object Promise]

1 comment:

Post Top Ad

Your Ad Spot