AppDividend
Latest Code Tutorials

Javascript Promise Example Tutorial

308

Get real time updates directly on you device, subscribe now.

Javascript Promise Example Tutorial.  JavaScript is the single-threaded scripting language. Everything happens in a sequence, it is written, line-by-line. But, in the asynchronous operations occur in the order they complete. Events are very good for things that can happen multiple times on the same object like keyup, touchstart, mouseover, etc. With those events, you don’t care about what happened before you attached a listener. But when it comes to the async behavior of success/failure, Callback functions are not as helpful as promises.

In the latest web development technologies, you have to deal with the asynchronous operation. Basically, the promises are a bit like event listeners except the following things.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial
  • The promise can only succeed or fail once. It cannot succeed or fail twice or more, neither can it switch from the success to failure or vice versa.
  • If the promise has succeeded or failed and you later add the success/failure callback, the correct callback will be called based on the output, even though the event took place earlier.
If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript Promise Example Tutorial

The promise constructor takes in one argument: a callback function with two parameters called resolve and reject. We can use promise as the two different approaches.

  1. Creating a Promise
  2. Consuming a Promise

#Creating a Promise

Let us take an example of how we can create a javascript promise.

// server.js

const prom = new Promise(function(resolve, reject) {
  setTimeout(() => {
    resolve('Promise is created and consumed');
  }, 200);
});

So, here, we have created one javascript promise object and passed the two parameters to the Promise constructor called resolve and reject. At the time of consuming, if the promise resolved then we can consume the value using then() function, if the promise is rejected then we get the error values inside the catch() block.

#Consuming a Promise

So, if we resolve the function, then we get the value inside then() block. Let us take the following example and see the output inside the terminal.

// server.js

const prom = new Promise(function(resolve, reject) {
  setTimeout(() => {
    resolve('Promise is created and consumed');
  }, 200);
});

prom.then(value => {
  console.log(value);
});

Now, run the above file in node.js by typing the following command.

 

Javascript Promise Example Tutorial

The promise is also rejected, and in that scenario, our code looks like below snippet.

// server.js

const prom = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('Promise is rejected');
  }, 200);
});

prom.catch(error => {
  console.log(error);
});

 

Javascript Promise reject

So understanding promises are not that difficult if the excellent example is provided.

The executor initiates some asynchronous work typically, and then, once that completes, either call the resolve function to resolve a promise or else rejects it if an error occurred. If the error is thrown in the executor function, it means that the promise is rejected. The return value of the executor is ignored.

#Promises States In Javascript

The Promise is the proxy for the value not necessarily known when a promise is created. Promise allows you to associate the handlers with an asynchronous action’s eventual success or failure reason. This lets asynchronous methods return the values like synchronous methods: instead of immediately returning a final value, an asynchronous method returns a promise to supply a value at some point in the future.

The Promise is in one of these states:

  • Pending: an initial state or pending state, neither fulfilled nor rejected.
  • Fulfilled: meaning that the operation completed successfully.
  • Rejected: meaning that the operation failed.
Related Posts
1 of 13

#Promise Methods

The Javascript Promise has the following methods.

Promise.all()

It returns the promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects the promise. If the returned promise fulfills, it is fulfilled with an array of the values from the fulfilled promises in the same order as defined in the iterable. If the returned promise rejects, it is rejected with the reason from the first promise in the iterable that rejected.

Promise.race(iterable)

It returns the promise that fulfills or rejects a.s.a. one of the promises in the iterable fulfills or rejects, with a value or reason from that promise.

Promise.reject(reason)

Returns the Promise object that is rejected with the given reason.

Promise.resolve (value)

It returns the Promise object that is resolved with the given value.

#Async-Await Promise Example

Let us take an example of how we can use Promise with the async-await.

// server.js

function square(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Math.pow(x, 2));
    }, 2000);
  });
}

async function layer(x)
{
  const value = await square(x);
  console.log(value);
}

layer(10); // 100

So, in the output, you will get the 100. First, it will call the async function layer and then it will wait for the promise to be either fulfilled or reject then it will give us the output.

Here, we have to use the setTimeout function to cause the manual delay of execution to simulate the AJAX request. If we reject then get the error object.

Error handling in Promises is very easy because it gives once whether fulfilled or rejected. So it is the best replacement to the callback functions where callback hell is created.

Finally, Javascript Promise Example Tutorial is over. Thanks for taking this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.