【发布时间】: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