首頁 > web前端 > js教程 > 主體

透過實際範例了解回調函數

王林
發布: 2024-07-19 12:21:28
原創
319 人瀏覽過

Understanding Callback Functions with a Practical Example

想像你是廚師並且你有一個幫手。你的工作是做飯,但首先,你需要從商店購買一些特殊的食材。你讓你的助手去商店,當他們回來時,他們告訴你他們有食材,這樣你就可以繼續做飯了。

我們需要什麼:

  • 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從網路上取得資料)。
  • 助手帶來配料並告訴你(使用獲取的數據呼叫回調函數)。
  • 您使用這些原料並繼續烹飪(處理獲取的數據)。

以上是透過實際範例了解回調函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!