【问题标题】:Callbacks, Promises, Async await in Javascript - still confusingJavascript 中的回调、承诺、异步等待 - 仍然令人困惑
【发布时间】:2018-01-21 10:50:23
【问题描述】:

我是 Javascript 新手,我看过很多视频,但我仍然无法理解回调、承诺和异步等待的确切用法。在这里,我编写了我所知道的小代码。

我的 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?

    });

如果我对回调,承诺的假设是错误的,请修改并解释。

帮帮我!

【问题讨论】:

  • 在你的回调解释中,你只是在使用一个承诺。要使用回调,只需使用您在选项中定义的函数。有名为 success 和 error 的选项参数或类似的名称。在你的承诺中,catch 似乎很奇怪,反而会失败。
  • 你能更新我的问题并发布一些答案吗?
  • 我建议不要在 AngularJS 中使用 async/await,直到您对两者都更加精通。 AngularJS 使用 $q 承诺,这些承诺具有一些特征,使它们与其他承诺实现(包括本机承诺,因此,异步/等待)真正不同。不小心混合 $q 和原生 Promise 会导致神秘的错误和不一致。请参阅stackoverflow.com/a/45119519/3731501 了解如何一起使用它们的一些想法。
  • 这个问题一直困扰着初学者。这是一个非常好的 Javascript 回调、promise 和 async-await 的演示视频。 youtube.com/watch?v=o2mkG_fxeGs

标签: javascript angularjs asynchronous callback promise


【解决方案1】:

回调只是一个函数,它作为参数传递给另一个函数,然后在其中执行。 Promise 只是一种也接受回调的模式。要在 javascript 中使用新的 async/await 模式编写相同的内容,您可以编写类似这样的内容。

注意控制器函数以 async 为前缀。

Async/await 只是让代码看起来更程序化。

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

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

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

【讨论】:

  • 如果你想让响应在作用域变量上可用,你需要运行 $scope.$apply()
  • 这里有一个例子,你可以看到它在工作codepen.io/richiemackay/pen/QaYZNj
【解决方案2】:

我能理解您的困惑,Promise 是在我们进行同步调用时使用的,即当您向服务器发送请求时,javascript 不会停止执行以下代码。当以下代码使用来自服务器请求的响应数据时,这可能会出现问题,因为服务器请求可能尚未完成。这是通过承诺解决的。 Javascript 的事件驱动方法为我们提供了两个事件,一个是 promise 被解决(服务器响应数据),另一个是 promise 被拒绝(服务器错误)。在.then 块中,我们可以调用使用响应数据的回调函数。在.catch 块中我们可以调用回调函数通知用户错误或重试服务器请求。

因此,我们可以调用.then.catch 函数的任何函数都是promise,我们在.then.catch 块中编写的函数称为回调函数。

【讨论】:

  • 谢谢,那什么是异步等待?
  • 只使用承诺和回调函数会创建回调地狱。我发现这篇文章真的很有帮助,希望对你也有帮助。 nikgrozev.com/2017/10/01/async-await
  • @MohamedSameer:您是在谈论 C# 异步和等待。 ?通过以下视频可以更好地理解 Javascript 承诺:youtube.com/watch?v=oa2clhsYIDY
猜你喜欢
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
  • 2019-05-05
  • 2018-10-17
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多