卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章67244本站已运行429

通过实际示例了解回调函数

通过实际示例了解回调函数

想象你是一名厨师并且你有一个帮手。你的工作是做饭,但首先,你需要从商店购买一些特殊的食材。你让你的助手去商店,当他们回来时,他们告诉你他们有食材,所以你可以继续做饭。

我们需要的:

  • node.js 安装在您的计算机上。
  • node-fetch 包,它帮助我们从互联网上获取数据。

安装 node.js 和 node-fetch

首先,确保你已经安装了 node.js。如果没有,您可以从nodejs.org下载并安装它。

然后,打开终端并通过运行以下命令安装 node-fetch 包:npm install node-fetch

示例:使用回调函数获取实际数据

以下示例展示了如何使用回调函数从 api 获取真实数据。

// function that fetches data from the api and then calls the helper (callback)
const fetchdata = async (callback) => {
  console.log('fetching ingredients from the store...');
  try {
    const fetch = (await import("node-fetch")).default;
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    const data = await response.json();
    console.log('ingredients have been fetched.');
    callback(data); // calling the helper (callback) with the fetched ingredients
  } catch (error) {
    console.error('error fetching ingredients:', error);
  }
};

// implementing and passing the helper (callback) to fetchdata
fetchdata((data) => {
  console.log('processing the fetched ingredients:', data);
});

代码说明:

1/ 函数fetchdata:

  • 把这个功能当成你去商店买食材的帮手吧。
  • 这个函数是异步的(async),这意味着它可以等待诸如获取数据之类的操作。
  • 它从 url https://jsonplaceholder.typicode.com/posts/1 获取数据,就像去商店购买特殊食材一样。
  • 成功获取数据后,将其转换为json格式,就像从商店带着食材回来一样。
  • 最后,它用获取的数据调用助手(回调函数)。

2/ 回调函数:

  • 这个功能就像厨师你在等待食材
  • 帮手拿来食材后,厨师(回调函数)使用它们继续烹饪。
  • 在我们的例子中,此函数将获取的数据记录到控制台。

运行代码

在 vs code 中打开终端(或使用命令行)并导航到 fetchdataexample.js 文件所在的目录。然后使用 node.js 运行此文件,命令为:node fetchdataexample.js

你应该看到什么:

当您运行此代码时,您应该看到类似这样的内容:

Fetching ingredients from the store...
Ingredients have been fetched.
Processing the fetched ingredients: { userId: 1, id: 1, title: '...', body: '...' }

概括:

  • 你是需要食材做饭的厨师。
  • 你的助手(回调函数)去商店获取原料(使用node-fetch从互联网上获取数据)。
  • 助手带上配料并告诉你(用获取的数据调用回调函数)。
  • 您使用这些原料并继续烹饪(处理获取的数据)。
卓越飞翔博客
上一篇: GitHub 上的新存储库 WebFormsJS 就在这里!
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏