Asynchronous Programming Module #20 Flashcards

1
Q

What arguments will setTimeout accept?

A

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

Callbacks are cool. But how would you write one? Hint: Think arrow function.

A

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

What’s a common strategy for error handling in callback functions?

A

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

What is a “promise” in JavaScript?

A

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.

««««&laquo_space;Extra Credit&raquo_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

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

What problem does the promise function solve?

A

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

What two methods are invoked after the promise function ends?

A

.then and .catch

Example code snippet below:

doSomething()
  .then((result) => {
    console.log(result)
  })
  .catch((error) => {
    console.log(error)
  })
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How is a promise object constructed?

A

const doSomething = ( ) => new Promise( )

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

What does it mean to resolve a promise?

A

Resolving a promise means complete it successfully (which results in calling the .then( ) method in who uses it).

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

What does it mean to reject a promise?

A

Rejecting a promise means ending it with an error which results in calling the .catch( ) method in who uses it.

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

How is an async function different than a promise function?

A

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

What is a use case where you absolutely need to terminate a code block with a semi-colon?

A

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.

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

What is the self-invoking function for and how is it written?

A
;( async ( ) => {
const result = await doSomething( )
console.log( result )
} ) ( )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What’s the Fetch API

A

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.

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

What are the advantages of async functions?

A

They are easily chain-able and much more readable than plain promises.

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

What would you use to delay the execution of function?

A

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

What’s the difference between setTimeout( ) and setInterval( ) ?

A

Instead of running the callback function once, it runs forever, for specified time duration defined in (miliseconds)

Example:
setInterval(() => {
  // runs every 2 seconds
}, 2000)
17
Q

How do you tell a setInterval( ) function to stop executing?

A

By using clearInterval( )

The function below runs every 2 seconds unless you tell it to stop, using clearInterval, passing it the interval id that setInterval returned:

const id = setInterval( ( ) => {
  // runs every 2 seconds
}, 2000)

clearInterval(id)