Promises 101: Javascript Promises Explained [with Code Snippets]

Promises 101: Javascript Promises Explained [with Code Snippets]

Javascript Promises explained with practical examples

Javascript Promises explained with practical examples

Prerequisites

Before you begin this tutorial you’ll need the following:

  • IDE (VS Code is used in this tutorial)
  • Basic understanding of Javascript ES6
  • Nodejs installed, you can get the latest version here.

Introduction

Working with data from other resources has brought the need to deal with asynchronous operations, ie operations that do not run in sequence. In this post, I explain, in simple terms one of the ways of handling asynchronous operations in Javascript, Promises. By the end of this post, you would understand Javascript Promises in code and simple English.

What are Javascript Promises?

According to the official documentation:

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

SYNTAX:

new Promise((resolve, reject)=>{})

In simpler terms, a Promise is an object that will return a particular value depending on the state of the Promise. A Promise can have one of three states

  • fulfilled
  • rejected
  • pending

STATE 1: Promise fulfilled

A promise has a state of fulfilledwhen it is resolved, meaning, nothing went wrong in the Promise and there are no errors. The code snippet below will return a state of fulfilled, because the Promise was resolved:

new Promise((resolve, reject)=>{
    resolve(console.log("Hello"))
})

RESULT:
"Hello"
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined

javascript

What is Geek Coin

What is GeekCash, Geek Token

Best Visual Studio Code Themes of 2021

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

Hire dedicated JavaScript Developers who are proficient in AngularJS, ReactJS, NodeJS, & VueJS frameworks. Get flexible hiring models as per your business requirements.

What is JavaScript - Stackfindover - Blog

What is PHP: - Who invented PHP, how it works, answers to all such questions about PHP, and much other information, you are going to

JavaScript Shopping Cart - Javascript Project for Beginners

JavaScript Shopping Cart - javascript shopping cart tutorial for beginnersBuy me a coffee 🍺 https://www.paypal.com/paypalme/ziddahSource Code: https://bit....

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

JavaScript compound assignment operators

We use assignment operator in JavaScript to store values in a variable. Read more...