」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > JavaScript 中的 Promise:理解、處理和掌握非同步程式碼

JavaScript 中的 Promise:理解、處理和掌握非同步程式碼

發佈於2024-11-07
瀏覽:879

Promises in JavaScript: Understanding, Handling, and Mastering Async Code

简介

我曾经是一名 Java 开发人员,我记得第一次接触 JavaScript 中的 Promise 时。尽管这个概念看起来很简单,但我仍然无法完全理解 Promise 是如何工作的。当我开始在项目中使用它们并了解它们解决的案例时,情况发生了变化。然后灵光乍现的时刻到来了,一切都变得更加清晰了。随着时间的推移,Promise 成为我工具带上的宝贵武器。当我可以在工作中使用它们并解决函数之间的异步处理时,这是一种奇怪的满足感。

您可能首先在从 API 获取数据时遇到 Promise,这也是最常见的示例。最近,我接受了采访,猜猜第一个问题是什么“你能告诉我 Promise 和 Async Await 之间的区别吗?”。我对此表示欢迎,因为我认为这是一个很好的起点,可以更好地了解申请人如何理解这些机制的运作方式。然而,他或她主要使用其他库和框架。它让我记下差异并描述处理异步函数错误的良好实践。

承诺是什么

让我们从最初的问题开始:“Promise 是什么?” Promise 是我们尚不知道的值的占位符,但我们将通过异步计算/函数得到它。如果承诺顺利的话,我们就会得到结果。如果 Promise 进展不顺利,那么 Promise 将返回错误。

Promise 的基本示例

定义一个承诺

通过调用 Promise 的构造函数并传递两个回调函数来定义 Promise:resolvereject.

const newPromise = new Promise((resolve, reject) => {
    resolve('Hello');
    // reject('Error');
});

当我们想要成功解析 Promise 时,我们调用解析函数。拒绝是在评估我们的逻辑过程中发生错误时拒绝承诺。

检索 Promise 结果

我们使用内置函数 then 来获取 Promise 的结果。它有两个传递的回调,结果和错误。当函数resolve成功解析Promise时,将调用结果。如果 Promise 未解决,则会调用第二个函数错误。该函数由拒绝或抛出的另一个错误触发。

newPromise.then(result => {
    console.log(result); // Hello
}, error => {
    console.log("There shouldn't be an error");
});

在我们的示例中,我们将得到结果 Hello,因为我们成功解决了 Promise。

承诺的错误处理

当 Promise 被拒绝时,总是会调用第二个错误回调。

const newPromise1 = new Promise((resolve, reject) => {
  reject('An error occurred in Promise1');
});

newPromise1.then(
  (result) => {
    console.log(result); // It is not invoked
  },
  (error) => {
    console.log(error); // 'An error occurred in Promise1'
  }
);

为了清晰起见,更推荐的方法是使用内置的 catch 方法。

const newPromise2 = new Promise((resolve, reject) => {
  reject('An error occurred in Promise2');
});

newPromise2
  .then((result) => {
    console.log(result); // It is not invoked
  })
  .catch((error) => {
    console.log(error); // 'An error occurred in Promise2'
  });

catch 方法是链接的,并提供了自己的错误回调。当 Promise 被拒绝时它会被调用。

两个版本都工作得很好,但链接在我看来更具可读性,并且在使用我们进一步介绍的其他内置方法时很方便。

连锁承诺

一个承诺的结果可能是另一个承诺。在这种情况下,我们可以链接任意数量的 then 函数。

getJSON('categories.json')
    .then(categories => {
        console.log('Fetched categories:', categories);

        return getJSON(categories[0].itemsUrl);
    })
    .then(items => {
        console.log('Fetched items:', items);

        return getJSON(items[0].detailsUrl);
    })
    .then(details => {
        console.log('Fetched details:', details);
    })
    .catch(error => {
        console.error('An error has occurred:', error.message);
    });

在我们的示例中,它用于缩小搜索结果范围以获取详细数据。每个 then 函数也可以有其错误回调。如果我们只关心捕获调用链中的任何错误,那么我们可以利用 catch 函数。如果任何 Promise 返回错误,它将被评估。

答应一切

有时我们想等待更多独立承诺的结果,然后根据结果采取行动。如果我们不关心 Promise 的解析顺序,我们可以使用内置函数 Promise.all。

Promise.all([
    getJSON('categories.json'),
    getJSON('technology_items.json'),
    getJSON('science_items.json')
])
    .then(results => {
        const categories = results[0];
        const techItems = results[1];
        const scienceItems = results[2];

        console.log('Fetched categories:', categories);
        console.log('Fetched technology items:', techItems);
        console.log('Fetched science items:', scienceItems);

        // Fetch details of the first item in each category
        return Promise.all([
            getJSON(techItems[0].detailsUrl),
            getJSON(scienceItems[0].detailsUrl)
        ]);
    })
    .then(detailsResults => {
        const laptopDetails = detailsResults[0];
        const physicsDetails = detailsResults[1];

        console.log('Fetched laptop details:', laptopDetails);
        console.log('Fetched physics details:', physicsDetails);
    })
    .catch(error => {
        console.error('An error has occurred:', error.message);
    });

Promise.all 接受 Promise 数组并返回结果数组。如果 Promise 之一被拒绝,则 Promise.all 也会被拒绝。

赛车承诺

另一个内置功能是 Promise.race。当你有多个异步函数 - Promise - 并且你想要对它们进行竞赛时,就会使用它。

Promise.race([
    getJSON('technology_items.json'),
    getJSON('science_items.json')
])
    .then(result => {
        console.log('First resolved data:', result);
    })
    .catch(error => {
        console.error('An error has occurred:', error.message);
    });

Promise 的执行可能需要不同的时间,Promise.race 会评估数组中第一个已解决或拒绝的 Promise。当我们不关心顺序但我们想要最快的异步调用的结果时使用它。

什么是异步等待

如您所见,编写 Promise 需要大量样板代码。幸运的是,我们有原生的 Async Await 功能,这使得使用 Promises 变得更加容易。我们用“async”这个词来标记一个函数,并且通过它,我们说在代码中的某个地方我们将调用异步函数,我们不应该等待它。然后使用await 字调用异步函数。

异步等待的基本示例

const fetchData = async () => {
    try {
        // Fetch the categories
        const categories = await getJSON('categories.json');
        console.log('Fetched categories:', categories);

        // Fetch items from the first category (Technology)
        const techItems = await getJSON(categories[0].itemsUrl);
        console.log('Fetched technology items:', techItems);

        // Fetch details of the first item in Technology (Laptops)
        const laptopDetails = await getJSON(techItems[0].detailsUrl);
        console.log('Fetched laptop details:', laptopDetails);
    } catch (error) {
        console.error('An error has occurred:', error.message);
    }
};

fetchData();

我们的 fetchData 被标记为异步,它允许我们使用await 来处理函数内的异步调用。我们调用更多的 Promise,它们会一个接一个地进行评估。

如果我们想处理错误,我们可以使用 try...catch 块。然后被拒绝的错误被捕获在 catch 块中,我们可以像记录错误一样对其采取行动。

有什么不同

它们都是 JavaScript 处理异步代码的功能。主要区别在于 Promise 使用 then 和 catch 链接时的语法,但 async wait 语法更多地采用同步方式。它使它更容易阅读。当异步等待利用 try...catch 块时,错误处理更加简单。这是面试时很容易被问到的问题。在回答过程中,您可以更深入地了解两者的描述并突出显示这些差异。

承诺功能

当然,您可以通过 async wait 使用所有功能。例如 Promise.all.

const fetchAllData = async () => {
    try {
        // Use await with Promise.all to fetch multiple JSON files in parallel
        const [techItems, scienceItems, laptopDetails] = await Promise.all([
            getJSON('technology_items.json'),
            getJSON('science_items.json'),
            getJSON('laptops_details.json')
        ]);

        console.log('Fetched technology items:', techItems);
        console.log('Fetched science items:', scienceItems);
        console.log('Fetched laptop details:', laptopDetails);
    } catch (error) {
        console.error('An error occurred:', error.message);
    }
};

实际用例

Promise 是 JavaScript 中处理异步代码的基本功能。主要使用方式如下:

从 API 获取数据

如上面的示例所示,这是 Promises 最常用的用例之一,您每天都会使用它。

处理文件操作

异步读写文件可以使用 Promise 来完成,特别是通过 Node.js 模块 fs.promises

import * as fs from 'fs/promises';

const writeFileAsync = async (filePath, content, options = {}) => {
    try {
        await fs.writeFile(filePath, content, options);
        console.log(`File successfully written to ${filePath}`);
    } catch (error) {
        console.error(`Error writing file to ${filePath}:`, error.message);
    }
};

const filePath = 'output.txt';
const fileContent = 'Hello, this is some content to write to the file!';
const fileOptions = { encoding: 'utf8', flag: 'w' }; // Optional file write options

writeFileAsync(filePath, fileContent, fileOptions);

基于 Promise 的库

Axios 是您应该熟悉的库。 axios在客户端处理HTTP请求,使用广泛。

Express 是 Node.js 的 Web 框架。它使构建 Web 应用程序和 API 变得容易,并且当您将 Promise 与 Express 结合使用时,您的代码将保持干净且易于管理。

带有示例的存储库

所有示例可以在:https://github.com/PrincAm/promise-example

概括

Promise 是 JavaScript 的基本组成部分,对于处理 Web 开发中的异步任务至关重要。无论是获取数据、处理文件还是使用 Axios 和 Express 等流行库,您都会经常在代码中使用 Promise。

在本文中,我们探讨了 Promise 是什么、如何定义和检索其结果以及如何有效地处理错误。我们还介绍了链接、Promise.all 和 Promise.race 等关键功能。最后,我们引入了 async wait 语法,它提供了一种更直接的方式来使用 Promise。

理解这些概念对于任何 JavaScript 开发人员来说都至关重要,因为它们是您日常依赖的工具。

如果您还没有尝试过,我建议您编写一个简单的代码片段来从 API 获取数据。您可以从一个有趣的 API 开始进行试验。另外,此存储库中提供了所有示例和代码片段供您探索。

版本聲明 本文轉載於:https://dev.to/princam/promises-in-javascript-understanding-handling-and-mastering-async-code-10kn?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3