Promises in javascript
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
- 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
Enhances readability of code unlike the repetitive callbacks
Defined and organized control of asynchronous logic
Promises vs callbacks
the code below shows repetitve callbacks
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:'joshuandeleva90@gmail.com'
})
} 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)
})