Asynchronous Programming Module #20 Flashcards
What arguments will setTimeout accept?
A FUNCTION and the TIME to wait before the function is executed. Here’s an example:
setTimeout( ( ) => { // runs after 2 seconds console.log('inside the function') }, 2000)
Callbacks are cool. But how would you write one? Hint: Think arrow function.
Assign a variable to an arrow func invoking the callback keyword. Here’s an example:
const doSomething = callback => { //do things //do things const result = 'test' callback(result) }
What’s a common strategy for error handling in callback functions?
By using error-first callbacks. The first parameter to be returned in this situation is the error object. If it returns NULL, all good. If there is an error a description of the error will be returned. Here’s an example of what one looks like.
s.readFile('/file.json', (err, data) => { if (err !== null) { //handle error console.log(err) return }
//no errors, process data console.log(data) })
What is a “promise” in JavaScript?
A Promise is an object that’s returned by a function that has not yet completed its work. The promise literally represents a promise made by the function that it will eventually return a result through the promise object.
When the called function finishes its work asynchronously, a function on the promise object called a resolution (or fulfillment, or completion) handler is called to let the original caller know that the task is complete.
«««««_space;Extra Credit»_space;»»»»»»»»»»»»»»
A Promise is in one of these states:
pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation was completed successfully. rejected: meaning that the operation failed.
Chained Promises
The methods promise.then( ), promise.catch( ), and promise.finally( ) are used to associate further action with a promise that becomes settled.
Read all about it! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
What problem does the promise function solve?
The main problem with this approach is that if we need to use the result of this function in the rest of our code, all our code must be nested inside the callback, and if we have to do 2-3 callbacks we enter in what is usually defined “callback hell” with many levels of functions indented into other functions:
doSomething((result) => { doSomethingElse((anotherResult) => { doSomethingElseAgain((yetAnotherResult) => { console.log(result) }) }) })
What two methods are invoked after the promise function ends?
.then and .catch
Example code snippet below:
doSomething() .then((result) => { console.log(result) }) .catch((error) => { console.log(error) })
How is a promise object constructed?
const doSomething = ( ) => new Promise( )
What does it mean to resolve a promise?
Resolving a promise means complete it successfully (which results in calling the .then( ) method in who uses it).
What does it mean to reject a promise?
Rejecting a promise means ending it with an error which results in calling the .catch( ) method in who uses it.
How is an async function different than a promise function?
An async function is a function declared with the async keyword, and the await keyword is permitted within them.
The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
The purpose of async/await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async/await is similar to combining generators and promises.
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.
For example, the following:
async function foo( ) {
return 1
}
…is equivalent to:
function foo( ) { return Promise.resolve( 1 ) }
What is a use case where you absolutely need to terminate a code block with a semi-colon?
A self invoking function. Such as this:
( ( ) => {
consoloe.log( ‘test’ )
} ) ( )
You will need the semi-colon on a line preceding the function or just before the first set of parenthesis.
What is the self-invoking function for and how is it written?
;( async ( ) => { const result = await doSomething( ) console.log( result ) } ) ( )
What’s the Fetch API
Fetch is used in AJAX calls to “FETCH” data, it is a native function in the browser. It’s an efficient way on snagging data from a server and adding it to a page without a need for a reload.
What are the advantages of async functions?
They are easily chain-able and much more readable than plain promises.
What would you use to delay the execution of function?
setTimeout( ) Example:
setTimeout( ( ) // runs after 2 seconds }, 2000
This syntax defines a new function. You can call whatever other function you want in there, or you can pass an existing function name, and a set of parameters:
const myFunction = (firstParam, secondParam) => { // do something }
// runs after 2 seconds setTimeout(myFunction, 2000, firstParam, secondParam)
setTimeout returns the timer id. This is generally not used, but you can store this id, and clear it if you want to delete this scheduled function execution:
const id = setTimeout(() => { // should run after 2 seconds }, 2000)
// I changed my mind clearTimeout(id)