Asynchrnouous Javascript Flashcards
(16 cards)
A _______ is a function that you
write and then pass to some other function
callback
One of the simplest kinds of asynchrony is when you want to run some
code after a certain amount of time has elapsed. As we saw in §11.10,
you can do this with the ___________ function
setTimeout()
The first argument to setTimeout() is a ______ and the second is
a _____ interval measured in milliseconds
function, time
A ______ is an object that represents the result of an asynchronous
computation
Promise
In other words, actions that we initiate now, but they finish later.
asynchronous actions
callback
When your done, call this
Why are callbacks necessary
Because in javascript operations that take a long time such as reading a file, network requets etc, the program could continue on even if that process has not finished exectuing, and if we try to access that later, could result in an error
The “producing code” takes whatever time it needs to produce the promised result, and the “______” makes that result available to all of the subscribed code when it’s ready.
promise
Constructor Syntax for promise object
let promise = new Promise(function(resolve, reject) {
// executor (the producing code, “singer”)
});
The function passed to new Promise is called the ______
executor
When new Promise is created, the ______ runs automatically. It contains the producing code which should eventually produce the result.
executor
Its arguments _____ and _____ are callbacks provided by JavaScript itself. Our code is only inside the executor.
resolve, reject
let promise = new Promise(function(resolve, reject) {
// the function is executed automatically when the promise is constructed
// after 1 second signal that the job is done with the result “done”
setTimeout(() => resolve(“done”), 1000);
});
The executor is called automatically and immediately (by new Promise).
The executor receives two arguments: resolve and reject. These functions are pre-defined by the JavaScript engine, so we don’t need to create them. We should only call one of them when ready.
After one second of “processing”, the executor calls resolve(“done”) to produce the result. This changes the state of the promise object:
then syntax
promise.then(
function(result) { /* handle a successful result / },
function(error) { / handle an error */ }
);
If we’re interested only in errors, then we can use ____ as the first argument: .then(null, errorHandlingFunction). Or we can use .catch(errorHandlingFunction), which is exactly the same:
null
The executor should call only ____ resolve or one reject. Any state change is final.
All further calls of resolve and reject are ______
one, ignored