Promises Flashcards
What is a promise?
It’s an object representing a value that may not be available yet, but will be at some point in the future.
It allows you to write asynchronous code in a more synchronous way.
What are the three states of a promise?
- pending - start
- fulfilled - with resolved value
- rejected - with a reason of rejection
How do you create a new promise?
const myPromise = new Promise(( resolve, reject ) => {});
Promise constructor and pass in a function (with 2 arg: res, rej) that defines the async operation.
What is promise chaining? And
What are some methods for handling promises?
Promise chaining is a way to write multiple async operations in a sequence, like:
.then() - handle a fulfilled promise,
.catch() - handle a rejected promise,
.finally() - run code after the promise settles.
What is async/await?
It’s a syntax that makes it easier to write async code using promises.
It allows you to write async code in a synchronous way, using the keywords async and await.
What is the difference between a promise and a callback?
Promise - structured way to handle asynchronous operations, provide readability and organization.
Callback - function invoked after a specific event or operation completes, can result in complex and nested code.
What is the difference between a promise and a callback?
Promise - structured way to handle asynchronous operations, provide readability and organization.
Callback - function invoked after a specific event or operation completes, can result in complex and nested code.
What are the pros and cons of using Promises instead of callbacks?
Pros
- Avoid callback hell which can be unreadable.
- Makes it easy to write sequential asynchronous code that is readable with .then().
- Makes it easy to write parallel asynchronous code with Promise.all().
- With promises, these scenarios which are present in callbacks-only coding, will not happen:
Call the callback too early
Call the callback too late (or never)
Call the callback too few or too many times - Fail to pass along any necessary environment/parameters
- Swallow any errors/exceptions that may happen
Cons
- Slightly more complex code (debatable).
- In older browsers where ES2015 is not supported, you need to load a polyfill in order to use it.