Promise Flashcards
A Promise
An object representing the eventual completion or failure of an asynchronous operation.
Guarantees that a promise comes with
- Callbacks will never be called before the completion of the current run of the JavaScript event loop
- Callbacks added with
then()
, even after a promise has been resolved or rejected, will still be called - Multiple callbacks may be added by calling
then()
several times.- each callback is executed one after another, in the order they were inserted
createAudioFileAsync(audioSettings).then(successCallback, failureCallback)
is shorthand for what?
const promise = createAudioFileAsync(audioSettings)
promise.then(successCallback, failureCallback)
Promise Chain
- Ability to execute two or more asynchronous tasks back-to-back
- Each subsequent operation starts when the previous succeeds, with the result from the previous step
Why must you always return results?
So that other callbacks will receive the results of a previous promise.
What is chaining after a catch
?
When you place a then()
after a catch()
to accomplish some actions even after there was a failure.
What is error propogation?
- When a promise chain stops if there’s an exception.
- It looks down the chain for catch handlers instead
- modeling
try
/catch
in synchronous code
- modeling
What are the only native asychronous functions in JavaScript?
setTimeout
and setInterval
What are three forms of asynchronous execution?
- Http requests
- Any I/O operation
- Dealing with a websocket
When does any function passed to setTimeout
execute?
- Executes asynchronously
- No less than the delay amount, but possibly more
- When the main thread is not busy anymore
Why is asynchronous code needed?
The main thread can’t execute the code and refresh the user interface at the same time.
What does the then
function do?
It binds one or two callbacks to the promise, and can use the data given to the resolve
or reject
function.
How many times can you call resolve
or reject
in a promise?
Just one. Calling resolve
or reject
more than once is useless as only the first one will be recognized.
When should you use Promise.resolve()
?
When you’re in a conditional and could either return a promise or a simple value. Use Promise.resolve(simpleValue)
so that a promise is always being returned.
function test() {
` if (something) {`
` return aNewPromise()`
` } else {`
` return Promise.resolve(42)`
` }`
}
How do you handle logging and recover from the error in a promise?
Simply use a catch
block to recover and send errors to logging, and then rethrow the error at the end of the catch
block using throw err
.
https://developers.google.com/web/fundamentals/primers/promises