Advanced JS Flashcards

1
Q

What are some ways of managing asynchronous code in JavaScript?

A

The current best practice for managing asynchronous code in JavaScript is to use the built in JavaScript Promise object. This will allow the program to execute an asynchronous function and still be able to run code in other parts of the program while waiting for the that asynchronous function to resolve. Another method would be to use callback functions which will mostly accomplish the same task, but can result in more complex and hard to read code when many callback functions are chained together (often referred to as callback hell).

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

What is a promise?

A
  • a promise is a guarantee of future value that can have three states: Pending, Resolved, and Rejected. When performing an asynchronous function in JavaScript, the return value will always be a promise, the state of which is determined by whether or not the function has successfully returned any value. If the Promise is pending, the function is still attempting to return a value, if it is resolved, it means the function has successfully returned a value, if it is rejected, then there was some kind of error or problem in returning a value.
    • when managing promises in JS, we have .then and .catch methods that can be used to handle what happens when a promise is no longer pending. .then will take a callback function to be performed when the promise is resolved and .catch will do the same for when the promise is rejected.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the differences between an async function and a regular function?

A

in JS, the program will not wait for a regular function to return anything before moving on to the next line of code. This can cause problems if the function is doing something time intensive like fetching data or making API calls. This problem is solved by async functions which always return a promise. This promise can then be handled in various ways depending on whether or not the promise is resolved either using .then and .catch statements or with async and await keywords that will pause the program until the promise is resolved.

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