Make Money Online HTML PHP JAVASCRIPT Async JS Crash Course – Callbacks, Promises, Async Await

Async JS Crash Course – Callbacks, Promises, Async Await

Async JS Crash Course – Callbacks, Promises, Async Await post thumbnail image


Async JavaScript Crash Course

Callback functions, promises, and async await are all ways of making asynchronous code easier to read and write. In this crash course, we’ll take a look at each of these concepts.

Callback Functions

Callback functions are functions that are called as a result of an asynchronous operation. For example, when you make a request to a web server, the server will send back a response. That response will be processed by a callback function that you provide.

Callback functions are often used to handle errors. For example, the following code uses a callback function to handle errors:

function loadData(url, callback) {

var xhr = new XMLHttpRequest();

xhr.onload = function() {

callback(null, xhr.responseText);

};

xhr.onerror = function() {

callback(xhr.statusText);

};

xhr.open(“GET”, url, true);

xhr.send();

}

loadData(” function(data, status) {

if (status === 200) {

console.log(data);

} else {

console.log(“Error: ” + status);

}

});

In the code above, the loadData() function makes a request to the Google website. The function takes two parameters: the URL of the website and a callback function. The callback function is called when the request is completed.

The callback function takes two parameters: data and status. The data parameter is the response from the Google website. The status parameter is the status code of the response.

If the status code is 200 (success), then the data parameter will contain the response from the Google website. If the status code is not 200, then the data parameter will contain the error message.

Promises

Promises are an alternative to callback functions. A promise is a object that represents the result of an asynchronous operation. The following code uses a promise to load data from the Google website:

function loadData(url) {

return new Promise(function(resolve, reject) {

var xhr = new XMLHttpRequest();

xhr.onload = function() {

resolve(xhr.

Related Post