🧵Promises In JavaScript🧵
✅Informative Thread with an Examples
#100DaysOfCode #CodeNewbie #javascript
" I promise to do this whenever that is true. If it isn't true, then I won't."
This is a simple illustration of JavaScript Promises. Sounds like an IF statement? We’ll soon see a huge difference.
- A promise is used to handle the asynchronous result of an operation.
- JavaScript is designed to not wait for an asynchrnous block of code to completely execute before other synchronous parts of the code can run.
For instance, when making API requests we have no idea if servers are offline or online & how long it takes to process server request. With Promises, we can defer execution of code until async request is completed. This way, other operations can keep running without interruption
Promises have three states:
- Pending: This is the initial state of the Promise before an operation begins
- Fulfilled: This means the specified operation was completed
- Rejected: The operation did not complete; an error value is usually thrown
Lets create promise,
If weather is true, resolve the promise returning the data dateDetails, else return an error object with data Bad weather, so no Date.
Using Promises
Using a promise that has been created is relatively straightforward; we chain .then() and .catch() to our Promise like so:
Since the weather value is true, we call mydate() and our console logs read:
We are going on a date!
{
name: 'Cubana Restaurant',
location: '55th Street'
table: 5
}
They come in handy a lot when making API requests and event handling. You can learn more about using promises is on below link :
developer.mozilla.org/en-US/docs/Web…
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.
