Async JS Flashcards
What is Async JS?
Async will execute a piece of code after a task that runs in a “background” complete. Async code is non-blocking, so the execution is not blocked. Example is setTimeOut function. After a certain period, the callback method will be called. Not all functions that accept callback is Async.
What is an API?
API is a piece of softwares that is invoked by another software.
How do you insert an HTML code in JS?
Use AddAdjacentHTML
How do you use XMLHttpRequest?
const request = new XMLHttprequest;
request.open(‘Get’, ‘https://www.google.com’);
request.send();
request.AddEventListener(‘load’, function(){
const [data] = JSON.parse(this.responseText);
});
What is callback hell?
CallBack hell happens when a callback method invokes another callback method and this goes on. Example, setTimeout will call another setTimeout in its callback method and so on. Callback hell makes code to look complex. We use promise to avoid call back hell.
What is a promise?
Promise is a placeholder for the future result of an Aync operation. We can take lottery as a analogy. When we buy a lottery, lottery ticket is a promise, when fullfilled the money is recieved as promised.
What is a lifecycle of a promise?
Pending->Settled. Settled can be either fulfiled or Rejected. Promise is settled only once.
How to consume a promise?
Promises can be consumed by registering functions using .then and .catch methods.
- then()
then() is invoked when a promise is either resolved or rejected. It may also be defined as a career which takes data from promise and further executes it successfully.
Parameters:
then() method takes two functions as parameters.
First function is executed if promise is resolved and a result is received.
Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method
Syntax:
.then(function(result){ //handle success }, function(error){ //handle error })
var promise = new Promise(function(resolve, reject) { resolve('Geeks For Geeks'); })
promise .then(function(successMessage) { //success handler function is invoked console.log(successMessage); }, function(errorMessage) { console.log(errorMessage); })
- catch()
catch() is invoked when a promise is either rejected or some error has occurred in execution. It is used as an Error Handler whenever at any step there is a chance of getting an error.
Parameters:
catch() method takes one function as parameter.
Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )
Syntax:
.catch(function(error){ //handle error }) Examples: Promise Rejected
var promise = new Promise(function(resolve, reject) { reject('Promise Rejected') })
promise .then(function(successMessage) { console.log(successMessage); }) .catch(function(errorMessage) { //error handler function is invoked console.log(errorMessage); });
Example of consuming a promise?
To consume a promise, we have to use THEN method. Then method accepts a function as a parameter. This function will have a parameter and that parameter is a RESOLVE respinse of the promoise.
function showImage(num) { return new Promise((resolve, reject) => { setTimeout(function () { resolve(`../images/${num}.jpg`); }, 1000 * num); }); }
const pro = showImage(1);
pro.then(function (path) {
document.getElementById(“image”).src = path;
});
Chain of promises?
showImage(1) .then(function (path) { document.getElementById("image").src = path; return showImage(2); ⚠ }) .then(function (path) { document.getElementById("image").src = path; return showImage(3);⚠ }) .then(function (path) { document.getElementById("image").src = path; return showImage(4);⚠ }) .then(function (path) { document.getElementById("image").src = path; return showImage(5);⚠ }) .then(function (path) { document.getElementById("image").src = path; return showImage(6);⚠ }) .catch((err) => alert(err));
IIFI way of calling aync function
async function renderImage() { try { const res = await showImage(1);
return res; } catch (error) { throw err; } }
//IIFI
(async function IFFIWithAync() { const res = await renderImage(); document.getElementById("image").src = res; })();
Async and await
Function which returns a promise can be wrapped inside a async function. We don’t need to call then , instead we can use await. However, async function returns a promise, which we have to call then if we need the return values.