Async Flashcards

(8 cards)

1
Q

What is a Promise, how to create and handle it (example)

A
  • The promise is an object representing the completion or failure of the async operation.

```javascript
function readFilePromise(fileName) {
return new Promise((resolve, reject) => {
fs.readFile(fileName, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}

readFilePromise(“1.txt”)
.then((data) => {
myText += data;
return readFilePromise(“3.txt”);
})
.catch((err) => {
// Catch any rejected promises.
console.log(Error! ${err});
})
.finally(() => {
runFinalCode();
});
~~~

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

List all Promise waiting patterns

A

Promise.all([ .. ])
- In classic programming terminology, a “gate” is a mechanism that waits on two or more parallel/concurrent tasks to complete before continuing.

Promise.race([ .. ])
- Promise.race is settled as soon as any of the promises you feed it settle, whether they are fulfilled or rejected.

Promise.any([ .. ])
- Promise.any is settled as soon as any of the promises you feed it is fulfilled or they are all rejected, in which case it’s rejected with an AggregateError.

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

Async / await example

A

async function hello() {
return “Hello”;
}

hello().then(console.log);

// Await must be used in an async function
await hello();

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

What is the output of this code:

```javascript
// Message queue example
{
console.log(“A”);

button.addEventListener(“click”, () => {
// Any other async code
console.log(“B”);
});

console.log(“C”);
}
~~~

A

Output: A C B

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

How to use a timeout

A
// Run after at least (!) 2 seconds (when call stack is empty)
let myGreeting = setTimeout(() => {
  alert("Hello, Mr. Universe!");
}, 2000);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to run a task immediately (after current job queue is emptied)

A
// Run as soon as all of the main thread has finished running
setTimeout(function () {
  alert("World");
}, 0);

// (NodeJS) Similar to setTimeout with 0 seconds.
setImmediate(() => {
  //run something
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to call a method every 1 second (and how to cancel it)

A
// Set
const createClock = setInterval(displayTime, 1000);

// Clear
clearInterval(myInterval);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to run code immediatelly (in next tick / animation frame), no delay of a job queue.

A
// Node
process.nextTick(() => {
  //do something
});

// Browser
function draw(timestamp) {
  // Drawing code goes here
  var rAF = requestAnimationFrame(draw);
}
cancelAnimationFrame(rAF);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly