JavaScript中Callbacks、Promises、Async/Await概念及代码改写求助
Clarifying Callbacks, Promises, and Async/Await in AngularJS
Hey there! Let's work through your questions to clear up the confusion around these asynchronous JavaScript concepts, and help you rewrite your code with async/await.
First: Are your Callback/Promise understandings correct?
Great start—your intuition is mostly right! Let's break it down:
- Callbacks: The
callbackandcallbackerrfunctions you defined are callbacks. These are functions you pass to another function (in this case, thethen()andcatch()methods of a Promise) to be executed later when an asynchronous operation finishes. Your first example uses named callbacks, while your second example uses anonymous callbacks directly insidethen()—both are valid callback patterns. - Promises: The
$httpservice in AngularJS returns a Promise by default. A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. When you chain.then()and.catch()onto it, you're handling the resolved (success) or rejected (error) states of that Promise. Both of your code blocks are working with Promises—you're just using different callback syntax in each.
Rewriting your code with Async/Await
Async/await is syntactic sugar over Promises—it makes asynchronous code look and behave more like synchronous code, which can be easier to read. Here's how to adapt your AngularJS controller code:
Updated script.js:
angular .module('myApp', []) .controller('myController', async function($scope, $http) { // Function to fetch animal name with async/await async function fetchAnimalName() { try { const response = await $http({ method: 'GET', url: 'animalname.json' }); console.log("Animal name:", response.data); } catch (error) { console.log("err:", error); } } // Function to fetch animal age with async/await async function fetchAnimalAge() { try { const response = await $http({ method: 'GET', url: 'animalage.json' }); console.log("Animal age: ", response.data); } catch (error) { console.log(error); } } // Call the async functions fetchAnimalName(); fetchAnimalAge(); });
Key Notes:
asynckeyword: We mark the controller function and each fetch function asasync—this tells JavaScript that these functions will containawaitexpressions.awaitkeyword: Placed before the$httpcall, this pauses the execution of the async function until the Promise returned by$httpresolves. The resolved value of the Promise is assigned toresponse.try/catchblocks: These replace the.then()(success) and.catch()(error) chains. If the Promise resolves, the code insidetryruns; if it rejects, the code insidecatchhandles the error.
If you want to run these requests sequentially (wait for one to finish before starting the other), you can call them in order inside another async block:
async function fetchAllData() { await fetchAnimalName(); await fetchAnimalAge(); } fetchAllData();
内容的提问来源于stack exchange,提问作者Sameer
相关产品推荐
相关产品推荐

