Sign in
Log inSign up

Basic Intro to Promises

Veera Venkata Avinash's photo
Veera Venkata Avinash
·Nov 14, 2017

A Brief Story About Promises Part 1

Promise: The Promise is an object represents the eventual completion or failure of asynchronous operation

Promise Based Example:


function getFirstUser(list){
    return new Promise((resolve, reject)=>{
        if(Array.isArray(list) === false){
            reject("List is not an array")
        }else if(list.length > 0){
            setTimeout(()=>{
                resolve(list[0])
            },2000)
        }else{
            reject(" List has no elements")
        }
    })
}


function getDetails(list){
    getFirstUser(list).then((user)=>{
        test(user)
    }).catch((e)=>{
        console.error(e)
    })
}


function test(user){
    console.log("------------",user) // after 2s user = 1
}

getDetails([1,2,3])

Traditional Approach:

function getDetails(list){
    let data = null;
    if(Array.isArray(list) === false){
        console.error("List is not an array")
    }else if(list.length > 0){
        setTimeout(()=>{
                data = list[0]
        },2000)
    }else{
        console.error(" List has no elements")
    }
    test(data)
}

function test(user){
    console.log("------------",user) //undefined
}
getDetails([1,2,3])

If you see traditional approach output function immediately invoked after last else case and result will be the undefined. Which is due to java script asynchronous nature even though JavaScript is synchronous code. To make it work perfectly take lot of pain

now lets consider Promise based approach:

output function invoked only after 2s ,it only because of promises, Promises make any asynchronous code acts like a sync code which make our code work perfectly

var promise = new Promise((resolve,reject)=>{
     //asynchronous code goes here
    on success call resolve(response)
    on falure call reject(error)
})

what ever the asynchronous code you have write it in above manner promise variable will returns a Promise. Now you can access the data by calling "then" call back function as mention below

promise.then((response)=>{
    console.log(response)
}).catch((e)=>{
    console.error(e)
});
Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct