Search code examples
javascriptangularjsasynchronouscallbackpromise

Callbacks, Promises, Async await in Javascript - still confusing


I am new to Javascript, i see lot of videos, still i cant understand this exact use of callbacks, promises and async await. Here i write small code upto my knowlege.

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) {


        // i think these 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);



        // i think these are promises
        $http({
            method: 'GET',
            url: 'animalage.json'
        }).then(function(response) {
            console.log("Animal age: ", response.data);
        }).catch(function(error) {
            console.log(error);
        })

        // i think to write new code in async await
        // how to write my above code using async await?

    });

Please modify and explain, if my assumption about callbacks,promises is wrong.

Help me!


Solution

  • A callback is simply a function that is passed as an argument into another function and then executed within. A promise is just a pattern that also accepts callbacks. To write the same thing using the new async/await pattern in javascript you could write something like this.

    Note the controller function is prefixed with async.

    Async/await just makes the code look more procedural.

    angular
        .module('myApp', [])
        .controller('myController', async function($scope, $http) {
    
            const response = await $http({
                method: 'GET',
                url: 'animalage.json'
            })
    
            console.log("Animal age: ", response.data);
        });