1

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!

Mohamed Sameer
  • 2,998
  • 3
  • 22
  • 51
  • In your callback explenation you're just using a promise. To use a callback there just use the functions you defined in the options. There are option parameters named success and error or something quiet similar. In your promise the catch seems quiet weird, it would be fail instead. – kevinSpaceyIsKeyserSöze Jan 21 '18 at 11:32
  • Can you update my question and post some answers? – Mohamed Sameer Jan 21 '18 at 11:44
  • I'd suggest to keep away from using async/await in AngularJS until you'll be more proficient with both. AngularJS uses $q promises which have some traits that make them really different from other promise implementations (including native promises and therefore, async/await). Mixing $q and native promises carelessly will cause cryptic bugs and inconsistencies. See https://stackoverflow.com/a/45119519/3731501 for some ideas how they can be used together. – Estus Flask Jan 21 '18 at 12:17
  • This question has always been troubling beginners. Here is a very good demo video for Javascript callbacks, promise and async-await. https://www.youtube.com/watch?v=o2mkG_fxeGs – Om Sao Sep 08 '20 at 01:04

2 Answers2

3

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);
    });
Richie Mackay
  • 1,385
  • 10
  • 12
2

I can understand your confusion, Promises are used when we do synchronous call i.e. when you send a request to server, javascript doesn’t stop execution of following code. This could be issue when following code uses response data from server request as server request may not have been completed yet. This is solved by promises. Javascript’s event driven approach gives us two events, One when promise is resolved (Server responded with data) and other when promise is rejected (Server error). In .then block, we can call the callback function which uses response data. And in .catch block we can call the callback function which notifies user about error or retry server request.

So any function on which we can call .then and .catch functions are promises, and functions we write in .then and .catch blocks are called callback functions.

  • Thanks, then what is async await? – Mohamed Sameer Jan 21 '18 at 11:55
  • Using only promises and callback functions creates callback hell. I found this article really helpful, I hope will help you too. http://nikgrozev.com/2017/10/01/async-await/ – nikhilkachare01 Jan 21 '18 at 12:03
  • @MohamedSameer: Are you talking about C# async and await. ? Javascript promise can be better understood by the following video: https://www.youtube.com/watch?v=oa2clhsYIDY – Varun Jan 21 '18 at 12:16