在现代的前端开发中,许多开发者会选择使用异步编程来提高程序的效率和性能,Node.js 和浏览器均支持这种方式。然而,由于异步函数的调用形式比较不同,也因此导致异步编程方式相对于同步编程的入门难度更高。为了解决这个问题,有不少的 npm 包被开发出来,其中就有 thenify 这个很受欢迎的包。本文将会向大家介绍如何使用 thenify。
什么是 thenify
thenify 是一个可以将回调函数形式的异步函数转换为 Promise 形式的库,从而更便于处理异步操作。主要的功能是将已经存在的回调式 API 转换为 Promises/A+ 规范的 API,以及提供了生成符合 Promises/A+ 规范的 methods 的函数。
如何使用 thenify
安装 thenify
作为一个 npm 包,使用 thenify 前,必须进行安装:
npm install thenify -g
使用 thenify
使用 thenify 来将一个函数转换为 Promise 的函数是非常简单的,其教程如下:
const thenify = require('thenify') const fs = require('fs') const stat = thenify(fs.stat)
其中,我们将 fs.stat 函数使用 thenify 转换为 Promise 函数,这个 Promise 函数返回的就是 stat 函数最终的结果,我们可以使用 then 和 catch 操作符进行回调处理。
另外,如果觉得代码不具备可读性,我们可以使用对象的方式进行转换:
const thenify = require('thenify') const fs = thenify(Object.assign({}, fs)) const stat = fs.stat
传递参数
如果需要传递参数,我们可以将它们作为要处理的函数的后续参数传递:
-- -------------------- ---- ------- ----- ------- - ------------------ ----- ------- - ------------------ ----- --- - -------------------- --- ----------- ----- ------- -- --------------------------- ------ ------ ----------- -- - --------------------- -- ------------ -- - ------------------ --展开代码
传递自定义的 Node.js 进程对象
在 Node.js 中,有时候我们需要传递一个自己创建的进程对象作为回调。在这种情况下,我们需要自己在 thenify 中传递自己的进程对象。假设自己创建了一个自己的子进程对象 child,那么在调用 thenify 时,只需要像下面这样传递即可:
const thenify = require('thenify') const child = require('child_process').fork() const stat = thenify(child.send.bind(child)) //传递自定义的进程对象
补丁
如果我们需要将 thenify 应用于原来的函数上,我们需要先将原来的函数进行补丁:
-- -------------------- ---- ------- ----- ------- - ------------------ ----- ------- - ------------------ --------------- -------- ----- --- - ----------- --- ----------- ----- ------- -- --------------------------- ------ ------ ----------- -- - --------------------- -- ------------ -- - ------------------ --展开代码
示例代码
-- -------------------- ---- ------- ----- ------- - ------------------ ----- ------- - ------------------ ---- ------- ------- ----- --- - -------------------- ---------------------------------- --------- ---------- --------------------- ----------- -- - -------------------------- -- ------------ -- - ------------------ --展开代码
结论
thenify 操作可以让 Node.js 异步编程变得更加简单和易学,并且使得代码可读性更高。这里推荐所有 Node.js 开发者在编写异步代码时,优先考虑使用 thenify 进行编程。同时也希望使用者在使用之前,结合本教程和个人使用经验,更好地理解和掌握 thenify 包的使用方法。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/40390