JavaScript Set 5 Flashcards
What does synchronous mean?
To be in a sequence such that every statement of the code is executed one by one.
A statement must wait for the earlier statement to complete
What does asynchronous mean?
To allow the program to be executed immediately without waiting for the earlier statement to complete
What is a Promise?
A JavaScript object that represents the eventual completion of an asynchronous operation and its resulting value.
It links the “producing code” and the “consuming code” together
How is a Promise like a proxy?
It allows you to associate handlers with an asynchronous action’s event on success or failure
What are the possible states of a promise?
- Fulfilled: Action related to a promise succeeding
- Rejected: Action related toa promise failing
- Pending: The initial state of the promise
What are the restrictions on promises moving between states?
- A promise cannot go from fulfilled to rejected or vice versa
- A promise cannot go from fulfilled or rejected to pending
What are the benefits of using Promises?
- Improves code readability
- Better handling of asynchronous operations
- Better flow of control definition in asynchronous logic
- Better error handling
- Avoid callback hell
- Better performance
What arguments does the Promise constructor take?
Takes one argument which is a callback function
What arguments does the Promise callback function take?
- Resolve function that is called if everything went well
- Reject function that is called if the callback function fails
What are the 3 main Promise instance methods?
- then(): invoked when a promise is resolved or rejected
- catch(): deals with rejected cases only
- finally(): Called whether or not the promise is resolved or rejected
What are the parameters accepted by the Promise’s then() method?
Takes 2 functions
1. Executed if the promise is resolved and a result is received
2. Executed if the promise is rejected and an error is received
What parameters are accepted by the catch() method?
Takes one function which is called when the promise is rejected
Since JavaScript already has try catch why does Promise need its own catch?
- try catch is used to handle synchronous errors but the Promise catch is used for asynchronous errors
- You often chain together Promises to perform a sequence of asynchronous tasks so you can go to the nearest catch function
What parameters are accepted by the finally() method?
Takes one function that is called when the Promise is resolved or rejected
What are the 3 main Promise static methods?
- all() waits for all promises to be resolved or one to be rejected
- any() returns a single promise that resolves with the value from the first Promise that resolved from an iterable of Promises
- race() waits until any of the promises are fulfilled or rejected