Sign in
Log inSign up

Promises in javascript

Joshua Ndeleva's photo
Joshua Ndeleva
·Aug 7, 2021·

2 min read

Promises basically are object that represent an operation that is not yet executed They take two parameter ie (resolve ,reject) whereby a resolve will show its' a sucess while resolve shows its' a fail

Reasons to why you should use promises

  1. Easy error handling
//load user posts
const loadUserPosts = (profile) =>new Promise((resolve ,reject)) =>{
  setTimeout(() => {
    if(profile){
      resolve([
        {
          id:1,
          title:"play tennis"
        },{
          id:2,
          title:"Do workouts"
        }
      ])
    }else{
     reject('Profile is required')
    }
  },1000)
} 
login('joshuandeleva90@gmail' ,'mypassword123')
  .then(user => loadUserProfile(user))
  .then(profile => loadUserPosts(profile))
  .then(posts => console.log(posts))
.catch(err => {
console.log(err)
})

2.Reduces coupling

  1. Enhances readability of code unlike the repetitive callbacks

  2. Defined and organized control of asynchronous logic

Promises vs callbacks

the code below shows repetitve callbacks promises .png

After refactoring the code use promises way To illustrate it i'm creating a login system whereby the user has to provide email ,password for login which he can create some posts and later pull the user profile together with the posts

const login = (email,password) => new Promise ((resolve ,reject)) => {
  setTimeout(() => {
    if(email && password){
      resolve({
        id:Date.now(),
        name:'Joshua',
        email:''
      })
    } else {

      reject('Email and password required')
    }
  },1000)  
} 
//load user profile
const loadUserProfile = (user) => new Promise ((resolve ,reject)) => {
  setTimeout(() => {
    if (user) {
      resolve({
        profileid:'myId',
        img:"images/proflie.img"
      })

    } else {
     reject('user is required')
    }
  },1000)
}
//load user posts
const loadUserPosts = (profile) =>new Promise((resolve ,reject)) =>{
  setTimeout(() => {
    if(profile){
      resolve([
        {
          id:1,
          title:"play tennis"
        },{
          id:2,
          title:"Do workouts"
        }
      ])
    }else{
     reject('Profile is required')
    }
  },1000)
} 
login('joshuandeleva90@gmail' ,'mypassword123')
  .then(user => loadUserProfile(user))
  .then(profile => loadUserPosts(profile))
  .then(posts => console.log(posts))
.catch(err => {
console.log(err)
})
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