You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 callback and callbackerr functions you defined are callbacks. These are functions you pass to another function (in this case, the then() and catch() 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 inside then()—both are valid callback patterns.
  • Promises: The $http service 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:

  1. async keyword: We mark the controller function and each fetch function as async—this tells JavaScript that these functions will contain await expressions.
  2. await keyword: Placed before the $http call, this pauses the execution of the async function until the Promise returned by $http resolves. The resolved value of the Promise is assigned to response.
  3. try/catch blocks: These replace the .then() (success) and .catch() (error) chains. If the Promise resolves, the code inside try runs; if it rejects, the code inside catch handles 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:38:28