Before you go, check out these stories!

0
Hackernoon logoJavaScript Promises from Scratch by@thejscode

JavaScript Promises from Scratch

Author profile picture

@thejscodeJaskirat Singh Grewal

Full Stack Web Developer. Kotlin/Flutter Mobile App Developer. ++Java/Scala/Python

To get the most out of this article, please make sure that you know basics about Synchronous and Asynchronous Programming and, if possible, about javascript callbacks.However, I will try to keep most of the stuff away from these topics so that you can understand at least 85% of it.

Understanding Promises

Suppose a friend comes to you for financial help and you promise him to give some cash after taking it out from an ATM.

  • You go to the ATM, swipe your card, and find out that your account has been frozen due to some reasons and you can't take out your money.
  • Then, you go back to your friend and tell him that you can't give him money because your account is frozen. Hence, breaking your promise.
//You have made promise to your friend and you leave for bank
if (everythingGoesWell) {
return theMoney //Promise is fulfilled
}
else {
return "Account_Frozen" //Promise failed
}

Promises are used in JavaScript to handle

async
operations. They are special objects that link the actual output (in the above example, it's required money) and the reason due to which we may not get the output (Account Frozen).

States of a Promise


A JavaScript

 promise
is either
settled
or
pending
. We can use the
Promise 
constructor to create a
promise
.

var thePromise = new Promise(executor())

The executor function is a callback of the promise constructor. It takes two callbacks: 

resolve
 and 
reject
, as arguments.

  1. The 
    resolve
     callback is used when the
    promise
    is actually fulfilled. It takes the output value as its argument.
  2. The 
    reject
     callback is used when the
    promise
    couldn't be fulfilled. It takes the reason as its argument.

When we create a

promise
it initializes in its 
pending
 state. Once the executor runs, the state changes to 
settled
 which can be either
resolved
 or 
rejected
.

    Implementation: Code Snippet

    var thePromise = new Promise(function(resolve,reject){
    // Try to take out money from atm
    withdraw(function(error,money) {
    // If withdrawal failed, tell why
    if (error) reject (error)
    // else return the money
    else resolve (money)
    })
    })

    Promises can be a bit of hectic stuff if you don't have experience with callbacks and callback hells. But once you grasp this concept, there is no going back!

    The 
    then
     and 
    catch
     clauses

    The 

    catch
     function is attached to
    promise
    which executes when the
    promise
    is rejected. It takes the error sent through 
    reject
     method as an argument.

    The 

    then
     function is attached to
    promise
    which executes when the
    promise
    is resolved. It sends the value sent through
    resolve
    method as an argument.

    There is a 

    finally
     clause too. It is executed no matter the
    promise
    resolves or rejects. It takes no arguments.

    var thePromise = new Promise(function(resolve,reject){
    // Try to take out money from atm
    withdraw(function(error,money) {
    // If withdrawal failed, tell why
    if (error) reject (error)
    // else return the money
    else resolve (money)
    })
    })
    
    thePromise.then(function(money) {
    // This function is executed when the above promise resolves and returns an //amount of money
    })
    
    thePromise.catch(function(error) {
    // This function is executed when the above promise rejects due to an error
    })
    
    thePromise.finally(function() {
    // This function is executed after the promise is resolved or rejected.
    })

    Thank You! Feedback, suggestions and corrections are highly appreciated. Please write in comments %-)

    Jaskirat S. Grewal (@thejscode)

    Previously published at https://dev.to/thejscode/javascript-promises-for-beginners-31aj

Author profile picture

@thejscodeJaskirat Singh Grewal

Read my stories

Full Stack Web Developer. Kotlin/Flutter Mobile App Developer. ++Java/Scala/Python

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!