gpt4 book ai didi

javascript - Javascript 中的回调、 promise 、异步等待 - 仍然令人困惑

转载 作者:行者123 更新时间:2023-11-30 08:24:10 25 4
gpt4 key购买 nike

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

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

});

请修改和解释,如果我关于回调, promise 的假设是错误的。

帮帮我!

最佳答案

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

注意 Controller 函数以 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);
});

关于javascript - Javascript 中的回调、 promise 、异步等待 - 仍然令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48365985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com