PHP前端开发

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

百变鹏仔 3天前 #JavaScript
文章标签 示例

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

我们需要的:

安装 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 fetchdatafetchdata((data) => {  console.log('processing the fetched ingredients:', data);});

代码说明:

1/ 函数fetchdata:

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: '...' }

概括: