回调,承诺,异步在Javascript中等待-仍然令人困惑 [英] Callbacks, Promises, Async await in Javascript - still confusing

查看:68
本文介绍了回调,承诺,异步在Javascript中等待-仍然令人困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java语言的新手,我看到了很多视频,但我仍然无法理解回调,promise和async等待的确切用法。

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.

我的index.html:

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.

帮帮我!

推荐答案

回调只是一个函数,它作为参数传递给另一个函数,然后在其中执行。一个promise只是一个也接受回调的模式。要在javascript中使用新的异步/等待模式编写相同内容,您可以编写如下内容。

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.

请注意,控制器函数的前缀为async。

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);
    });

这篇关于回调,承诺,异步在Javascript中等待-仍然令人困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆