Understanding Promises in Javascript

Categories Javascipt, Software Development
asynchronous

In this blog post I´d like to tell you what I learned in the course I´m taking about NodeJS. I decided to document every Section what I learned.
In section 3 of my NodeJS course I came accross Promises in javascript, I´d like to know more about Promises. So I decided to write a blog post about it, hope you enjoy it and learned something new.

1. Creating a Promise
2. Promise Chaining

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:

  • Promise is pending: You don´t know if you will get a response -> aysnchronous operation is not yet completed
  • Promise is resolved: The Request was successfull to the server and it response with data -> asynchronous operation has completed
  • Promise is rejected: The Request was not successfull to the server due a network error -> asynchronuos operation failed

Creating a Promise
Syntax of a Promise:

Let´s write a function that return a Promise. This Promise is going to handle a Request to a Server or API.

First let´s start of with installing request. With this library we can do http request out of Node. Go to the directory you where you want to install Request. and type in

requestSo now let’s use our new installed Package:

So what does this promise do ?
This Promise ask the Github API to make an GET Request to URL https://api.github.com/users/rayleigh3105 (my user).
At first we check if the response of the github API does contain a Error object. If not we print out the data from the server and resolve the Promise.

This is the OUTPUT:

2. Chaining Promises

Chaining promises can make asynchronous code flow synchronously.

My last post about NodeJs.

Greetings

Moritz 😀

1 thought on “Understanding Promises in Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *