async await vs promises

1
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(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();
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.

Syntax:
let promise = new Promise(function(resolve, reject) {
  // some stuff
});

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

console.log(promise1);
// expected output: [object Promise]


Tags

Post a Comment

1Comments
Post a Comment