Async Flashcards
(8 cards)
What is a Promise
, how to create and handle it (example)
- 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();
});
~~~
List all Promise waiting patterns
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.
Async / await example
async function hello() {
return “Hello”;
}
hello().then(console.log);
// Await must be used in an async function
await hello();
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”);
}
~~~
Output: A C B
How to use a timeout
// Run after at least (!) 2 seconds (when call stack is empty) let myGreeting = setTimeout(() => { alert("Hello, Mr. Universe!"); }, 2000);
How to run a task immediately (after current job queue is emptied)
// 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 to call a method every 1 second (and how to cancel it)
// Set const createClock = setInterval(displayTime, 1000); // Clear clearInterval(myInterval);
How to run code immediatelly (in next tick / animation frame), no delay of a job queue.
// Node process.nextTick(() => { //do something }); // Browser function draw(timestamp) { // Drawing code goes here var rAF = requestAnimationFrame(draw); } cancelAnimationFrame(rAF);