JavaScript Promises In 10 Minutes | Understanding JavaScript Promises in Simple English

preview_player
Показать описание
Promise explained in simple English :

Understanding JavaScript Promises in Simple English

Let us consider Father & son scenario :

Son - Loves playing games - GTA (mobile, PC and PS4)

1. Son playing game - Mobile - PS4
Son wants to play GTA in PS4 and asks his father to buy him a PS4.
2. Father says yes he will get him one as he is going out now.
3. Meanwhile son says i will continue to play this game in mobile as he can earn more rewards
instead of stiing idle.
4.Son says to father if he gets the PS4 then father should call him so that son can do intial setup
of PS4 and if he doesnot get PS4 then son can play same game in PC too.
5. Father promises that he will get PS4 and he will call to inform the status.

Analyze in Javascript Terms

1. Father - Promise
2. Son says i will continue to play this game in mobile
as he can earn more rewards
instead of stiing idle. - Asynchronous operation in javascript
3. Son gets PS4 - Fullfilled
4. He will do intial setup Success calback
5. Son doesnt get PS4 Rejected
6. He will play PC Failure Callback
7. Father goes out to buy
before calling son Pending

Promise :
It an object in javascript

Always be in one of three states

1. Pending : Father goes out to buy before calling son - (PS4/not)
2. Fullfilled : Son gets PS4
3. Rejected : Son doesnt get PS4

Code :

let promiseToBuyPS4 = new Promise(function(resolve,reject){
//condition son gets PS4
let gotPS4 = false

if(gotPS4){
resolve('Yippe Got PS4')
}else{
reject('Back to PC Games')
}
});

}).catch(function(fromReject){
})

Next Steps :

---------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------
Must Watch Playlists

---------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------

#promises
#promisesinjavascript
#callbacks
Рекомендации по теме