”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > JavaScript 中的 Promise:理解、处理和掌握异步代码

JavaScript 中的 Promise:理解、处理和掌握异步代码

发布于2024-11-07
浏览:619

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]删除
最新教程 更多>
  • 如何干净地删除匿名JavaScript事件处理程序?
    如何干净地删除匿名JavaScript事件处理程序?
    删除匿名事件侦听器将匿名事件侦听器添加到元素中会提供灵活性和简单性,但是当要删除它们时,可以构成挑战,而无需替换元素本身就可以替换一个问题。 element? element.addeventlistener(event,function(){/在这里工作/},false); 要解决此问题,请考虑...
    编程 发布于2025-07-12
  • Python中何时用"try"而非"if"检测变量值?
    Python中何时用"try"而非"if"检测变量值?
    使用“ try“ vs.” if”来测试python 在python中的变量值,在某些情况下,您可能需要在处理之前检查变量是否具有值。在使用“如果”或“ try”构建体之间决定。“ if” constructs result = function() 如果结果: 对于结果: ...
    编程 发布于2025-07-12
  • Python环境变量的访问与管理方法
    Python环境变量的访问与管理方法
    Accessing Environment Variables in PythonTo access environment variables in Python, utilize the os.environ object, which represents a mapping of envir...
    编程 发布于2025-07-12
  • 如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction:Inserting data into a MySQL database can...
    编程 发布于2025-07-12
  • 反射动态实现Go接口用于RPC方法探索
    反射动态实现Go接口用于RPC方法探索
    在GO 使用反射来实现定义RPC式方法的界面。例如,考虑一个接口,例如:键入myService接口{ 登录(用户名,密码字符串)(sessionId int,错误错误) helloworld(sessionid int)(hi String,错误错误) } 替代方案而不是依靠反射...
    编程 发布于2025-07-12
  • 如何使用Regex在PHP中有效地提取括号内的文本
    如何使用Regex在PHP中有效地提取括号内的文本
    php:在括号内提取文本在处理括号内的文本时,找到最有效的解决方案是必不可少的。一种方法是利用PHP的字符串操作函数,如下所示: 作为替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式来搜索特...
    编程 发布于2025-07-12
  • Java的Map.Entry和SimpleEntry如何简化键值对管理?
    Java的Map.Entry和SimpleEntry如何简化键值对管理?
    A Comprehensive Collection for Value Pairs: Introducing Java's Map.Entry and SimpleEntryIn Java, when defining a collection where each element com...
    编程 发布于2025-07-12
  • JavaScript计算两个日期之间天数的方法
    JavaScript计算两个日期之间天数的方法
    How to Calculate the Difference Between Dates in JavascriptAs you attempt to determine the difference between two dates in Javascript, consider this s...
    编程 发布于2025-07-12
  • 如何使用组在MySQL中旋转数据?
    如何使用组在MySQL中旋转数据?
    在关系数据库中使用mySQL组使用mySQL组进行查询结果,在关系数据库中使用MySQL组,转移数据的数据是指重新排列的行和列的重排以增强数据可视化。在这里,我们面对一个共同的挑战:使用组的组将数据从基于行的基于列的转换为基于列。 Let's consider the following ...
    编程 发布于2025-07-12
  • 使用jQuery如何有效修改":after"伪元素的CSS属性?
    使用jQuery如何有效修改":after"伪元素的CSS属性?
    在jquery中了解伪元素的限制:访问“ selector 尝试修改“:”选择器的CSS属性时,您可能会遇到困难。 This is because pseudo-elements are not part of the DOM (Document Object Model) and are th...
    编程 发布于2025-07-12
  • 在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    For Each Loop vs. Iterator: Efficiency in Collection TraversalIntroductionWhen traversing a collection in Java, the choice arises between using a for-...
    编程 发布于2025-07-12
  • 人脸检测失败原因及解决方案:Error -215
    人脸检测失败原因及解决方案:Error -215
    错误处理:解决“ error:((-215)!empty()in Function Multultiscale中的“ openCV 要解决此问题,必须确保提供给HAAR CASCADE XML文件的路径有效。在提供的代码片段中,级联分类器装有硬编码路径,这可能对您的系统不准确。相反,OPENCV提...
    编程 发布于2025-07-12
  • Async Void vs. Async Task在ASP.NET中:为什么Async Void方法有时会抛出异常?
    Async Void vs. Async Task在ASP.NET中:为什么Async Void方法有时会抛出异常?
    在ASP.NET async void void async void void void void void的设计无需返回asynchroncon而无需返回任务对象。他们在执行过程中增加未偿还操作的计数,并在完成后减少。在某些情况下,这种行为可能是有益的,例如未期望或明确预期操作结果的火灾和...
    编程 发布于2025-07-12
  • 如何使用Python理解有效地创建字典?
    如何使用Python理解有效地创建字典?
    在python中,词典综合提供了一种生成新词典的简洁方法。尽管它们与列表综合相似,但存在一些显着差异。与问题所暗示的不同,您无法为钥匙创建字典理解。您必须明确指定键和值。 For example:d = {n: n**2 for n in range(5)}This creates a dicti...
    编程 发布于2025-07-12
  • 在Python中如何创建动态变量?
    在Python中如何创建动态变量?
    在Python 中,动态创建变量的功能可以是一种强大的工具,尤其是在使用复杂的数据结构或算法时,Dynamic Variable Creation的动态变量创建。 Python提供了几种创造性的方法来实现这一目标。利用dictionaries 一种有效的方法是利用字典。字典允许您动态创建密钥并分...
    编程 发布于2025-07-12

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3