Promises Flashcards

1
Q

What is a promise?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the three states of a promise?

A
  • pending - start
  • fulfilled - with resolved value
  • rejected - with a reason of rejection
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you create a new promise?

A

const myPromise = new Promise(( resolve, reject ) => {});

Promise constructor and pass in a function (with 2 arg: res, rej) that defines the async operation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is promise chaining? And
What are some methods for handling promises?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is async/await?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the difference between a promise and a callback?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the difference between a promise and a callback?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the pros and cons of using Promises instead of callbacks?

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly