Sumit | Javascript + React
Sumit | Javascript + React

@sumitsaurabh927

11 Tweets Jun 09, 2022
๐Ÿ“Œ Understand Promises in 9 simple tweets
๐Ÿค” What are Promises?
๐Ÿ—ƒ๏ธ Well, promises are Javascript objects that may have some value in the future.
๐Ÿ™Œ Didn't understand? Don't worry, let's take an example:
๐Ÿฅฒ Suppose you're a student and you're bad at Chemistry (I didn't have to 'suppose' back in my school days).
๐Ÿช… Your chemistry teacher is concerned and she wants you to score good marks.
๐ŸŒŸ So she makes a 'promise' to you saying if you score more than 90 marks in the upcoming test, she'll give you a prize.
๐Ÿ”‘ Now, she hasn't given you any prize yet, but she'll if you score good marks!
๐Ÿ’ญ Promises in Javascript are quite similar.
โณ Many times, we need to give some time for an operation to finish (think of letting an API fetch some data in the background).
๐Ÿ™‡ We can't make the user wait for that.
๐Ÿ‘‰ So what we do is that we make use of a promise and Javascript continues executing knowing that it'll get a result (like how the teacher will give a prize, in the future)
๐Ÿ’ก This way, we get to do any operation that is going to take time without halting everything else.
๐Ÿ‘‡ Now, promises have three states:
๐Ÿ•ก Pending
โœ… Resolve
โŒ Reject
๐ŸคŒ They're all quite simple but let's understand each one of them:
โฑ๏ธ Pending:
๐Ÿค— It is exactly what it sounds like and it is the default state of a promise until a promise is completed either successfully or unsuccessfully.
๐Ÿ“ So, unless the job is performed successfully or unsuccessfully, the default state of a promise is 'pending'.
โœ… Resolve:
๐Ÿค Read resolve, think success, because when the job is successfully completed, the state of a promise changes from 'pending' to 'resolved', since the promise has been 'resolved'.
๐Ÿ… So, from now on, read resolve, think success!
โŒ Reject:
๐Ÿ‘‰ It does exactly what it sounds like.
โ›” When the pending task in a promise fails, the state of the promise is 'reject' as the task was 'rejected'.
โœจ That's how simple it is!
๐Ÿ“ Also, note that a promise returns an object by default and you're good to go.
๐ŸŽฏ This is a part 1/2 of my promise thread and I 'promise' to do the second part tomorrow.
๐Ÿš€ The current state of my promise is 'pending' but it'll be 'resolved' tomorrow.
๐ŸคŒ Stay tuned!
๐Ÿ‘‰ I write daily threads on web dev so if you enjoyed this thread, please:
โœ… Follow me @sumitsaurabh927 for more of these.
โœ… RT the tweet below to show me some ๐Ÿงก and comment your thoughts.
๐ŸŒŸ Your each like, every comment motivates me to come up with awesome new stuff!

Loading suggestions...