Menu
Coddy logo textTech

Promises

Lesson 8 of 9 in Coddy's Tricky parts of Modern Javascript (ES6+) course.

Sometimes we need to perform some tasks , which may take some time to complete. 

Such code cannot be written in normal synchronous way, thus they are called Asynchronous or simply async tasks.

Promises are Javascript objects that ensure the completion of async tasks and return the result , it can be either success or failure !

A promise can have three states : 1. Pending ( initial state ) 2. Fulfilled (it returns the result) 3. Rejected (it returns an error)

let myPromise = new Promise(function(resolve, reject) {

  resolve("Everything is fine"); // this callback is called if task is successful
  reject("Error");  // this callback is called if task is failed
  
});

// Or with arrow function
let myPromise2 = new Promise((resolve, reject) => {//code});

here myPromise is a promise object. The callback resolve is called if the promise is fulfilled, reject is called if the promise is rejected.

myPromise.then( value => console.log(value)) // Everything is fine
		 .catch( error => console.log(error)) // Error		

for accessing the value of result, if the promise is successful, we can use .then( value => // your code ) . if promise is rejected , we can use .catch( value => // your code ).

Promises are generally used in async tasks ex. while calling backend APIs (front-end) , database requests( backend ) etc.

challenge icon

Challenge

Medium

Write a function getPromise which returns a promise which resolves the same string or reject with the string "Rejected" if the input string is "Coddy"

Try it yourself

function getPromise(s) {
  // Write code here
}

All lessons in Tricky parts of Modern Javascript (ES6+)