"Confused by Callbacks, Promises, and Async Await in JavaScript? You're not

After watching numerous videos on Javascript, I am still struggling to grasp the concepts of callbacks, promises, and async await. Below is a snippet of code that I have put together based on my current understanding.

Here is my index.html:

<!DOCTYPE html>
<html lang="en" ng-app='myApp'>

<head>
    <meta charset="UTF-8>
    <title>Index</title>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
    <script src='script.js'></script>
</head>

<body ng-controller='myController'>

</body>

</html>

script.js:

angular
    .module('myApp', [])
    .controller('myController', function($scope, $http) {


        // Here, I am using what I believe are callbacks
        function callback(response) {
            console.log("Animal name:", response.data);
        }
        function callbackerr(response) {
            console.log("err:", response);
        }
        $http({
                method: 'GET',
                url: 'animalname.json'
            }).then(callback)
            .catch(callbackerr);



        // Now, I am working with what I think are promises
        $http({
            method: 'GET',
            url: 'animalage.json'
        }).then(function(response) {
            console.log("Animal age: ", response.data);
        }).catch(function(error) {
            console.log(error);
        })

        // I am interested in learning how to convert this code to use async await
        // Could you provide guidance on how to do so?

    });

If my understanding of callbacks and promises is incorrect, please correct me and provide some insights!

I appreciate any help!

Answer №1

A callback is essentially a function that is given as a parameter to another function and then executed within it. A promise, on the other hand, follows the same concept but also allows for callbacks. When utilizing the new async/await feature in javascript, you can achieve similar functionality with cleaner code.

It's important to note that the controller function must start with the async keyword.

The async/await approach simplifies the code and makes it appear more step-by-step.

angular
    .module('myApp', [])
    .controller('myController', async function($scope, $http) {

        const response = await $http({
            method: 'GET',
            url: 'animalage.json'
        })

        console.log("Animal age: ", response.data);
    });

Answer №2

It's common to feel puzzled by this concept, but Promises play a crucial role in managing asynchronous operations in JavaScript. When making a server request, using Promises ensures that the rest of the code can continue running without waiting for the response. This eliminates potential issues that may arise if the code tries to access data from the server before the request is complete.

With JavaScript's event-driven model, Promises offer two events: one when the promise is resolved (indicating successful data retrieval from the server) and another when it is rejected (indicating an error on the server). By utilizing the .then block, we can execute a callback function that processes the response data, while the .catch block handles errors or allows for retrying the server request.

Any function that supports .then and .catch calls is considered a Promise, with the functions defined within these blocks referred to as callback functions.

Answer №3

Callback functions are a powerful concept in programming where a function can be passed as an argument to another function for later use in handling asynchronous tasks.

Promises provide a more updated and efficient way of managing asynchronous operations compared to nested Callbacks, preventing the infamous "Callback Hell" issue.

Async/Await simplifies working with Promises, offering a more intuitive approach to handling asynchronous tasks.

If you're interested in learning more about Async/Await and its evolution, I recommend checking out this informative article:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Receiving empty req.body data from a POST request in Express.js when using body-parser

In my development process, I am utilizing the Express and body-parser middleware for handling incoming requests. The front end consists of a form with a hidden input and a submit button created in Pug: form(notes="saveNotesForm" action=`/lessons/${lesson. ...

What is the best way to inform the DOM about newly generated elements dynamically?

When making an AJAX call and generating HTML on the backend side, the result may not display with the desired properties such as cursor styling. For example, using jQuery to render JSON data: $(data.message).each(function (index, value) { $('#sta ...

When comparing two state arrays in React, it is important to note that they will not be considered equal and return a boolean (True

As I attempt to compare two arrays stored in my state, my goal is to set a boolean variable to "true" if they match. However, my current if statement fails to detect equality between the arrays. I'm performing this comparison within a setInterval() f ...

Middleware that is commonly used by both error handling and regular request-response chains

I am currently working on implementing a middleware that can set a variable in the sequence of both error and non-error scenarios. Is there a way to achieve this without disrupting the normal flow of middleware? Specifically, when I include the err param ...

Is it possible to determine if the user is able to navigate forward in browser history?

Is there a way to check if browser history exists using JavaScript? Specifically, I want to determine if the forward button is enabled or not Any ideas on how to achieve this? ...

Steps for embedding a "string includes" functionality within an Angular filter

Currently, I am in the process of implementing a filtering system using checkboxes. Within my geojson data, there is a property called "status" which can have values like: status : "Act 3Q99" or status : "Fut 3Q99" My objective is to filte ...

Wordpress contact form not functional with AJAX feature currently experiencing issues

I am currently working on a Wordpress website and facing an issue with creating a form using an ajax call that should appear on every product page. The code worked smoothly on other servers, but when I integrated it into my Wordpress site (using Woocommerc ...

The duration of token validity in Node.js using JWT never ceases

When I create a JWT token using jsonwebtoken and set it to expire after 5 minutes, the token never actually expires. The issue is that I always get the iat (issued at) and exp (expiration) times as the same timestamp, as shown in the log below: { sub: ...

Updating the data-tooltip via AJAX is not functioning as expected

In my html template, there is a button: <a class="tooltipped" id="stash_recipe_tooltip" data-position="bottom" data-delay="50" data-tooltip="{{ stash_tooltip }}"> <div id="stash_recipe_btn" class="detail ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

Is the callback still triggered even after the off function is called?

Can someone help me with a scenario where despite calling the off on a reference, the callbacks are still being triggered repeatedly? var ref = new Firebase('https://example.firebaseio.com/123456'); for (var n = 0; n < 1024; ++n) { ref.pus ...

Database query failing to make any changes

Currently, I am facing an issue where I am attempting to update a value in a table based on a specific condition being met, but for some reason the update is not taking place: if (req.headers['user-agent'].includes('HeadlessChrome') ...

Making a RESTful API call using JavaScript

Can someone help me with making a call to a REST API using JavaScript, Ajax, or jQuery? curl -v -X PUT -H "Content-Type: application/json" -H "Accept: application/json" -X PUT --user user:password http://url -d "{\"name\": \"Marcus0.2\ ...

Python - utilizing webdriver with asynchronous functions

Is it possible to open a browser for each task first and then load links afterwards? The code below raises an error: import asyncio from selenium import webdriver async def get_html(url): driver = await webdriver.Chrome() response = await driver. ...

Switching focus between windows while working with React

My current setup involves using React. Every time I run yarn start, I can begin coding and see the changes in my browser. However, there's a recurring issue where my terminal keeps notifying me about errors in my code every 10 seconds or so. This cons ...

Exploring SVG Morphing Reversal Techniques in Anime.js

I have been trying to implement direction: 'reverse' and timeline.reverse(), but so far it hasn't been successful. Interestingly, when I set loop: true, the reverse animation can be seen within the loop. However, my goal is to trigger this a ...

Proper usage of a method within another method in a Vue component

Currently, I am extracting GPS data from an image using exifjs. My objective is to convert the latitude and longitude variables into a decimal variable as illustrated below: <template lang="html"> <div class="upload-wrap"> <button cla ...

Is it possible to customize a loaded webpage on WebView by adding scripts or styles?

I am in the process of developing a web browser that allows users to easily hide distracting elements while reading content. I believe the most effective way to hide user-selected divs would be by tweaking the source code (html) of the loaded page. Howeve ...

Is there a method to send a FontAwesomeIcon component as a prop to the ReactHTMLTableToExcel component?

When using ReactHTMLTableToExcel, you can set the prop buttonText as a String, <ReactHTMLTableToExcel id="test-table-xls-button" className="download-table-xls-button" table="table-to-xls" ...

Connecting a Kendo Dropdown menu to external data sources for seamless integration

I need help with binding data to a dropdown list for my local service. Whenever I try to download the data, I keep getting an error message: Uncaught SyntaxError: Unexpected token: Does anyone have any ideas on how to resolve this issue? This is my JS ...