search
HomeWeb Front-endJS TutorialExplanation of related content of util.promisify

Explanation of related content of util.promisify

Oct 18, 2018 pm 02:19 PM
javascriptnode.jspromise

This article brings you some explanations about util.promisify. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

util.promisify is a new tool in node.js 8.x version. It is used to convert the old Error first callback into a Promise object, making it easier to transform old projects.

Before the official launch of this tool, there were already many similar tools in the private sector, such as es6-promisify, thenify, and bluebird.promisify.

and many other excellent tools have implemented this function, helping us to avoid having to worry about re-implementing various codes using Promise when dealing with old projects.

The general idea of ​​​​implementing the tool

First of all, we need to explain the general idea of ​​​​implementing this tool, because there is a convention for asynchronous callbacks in Node: Error first, that is It is said that the first parameter in the callback function must be an Error object, and the remaining parameters are the correct data.

After knowing this rule, the tool can be easily implemented. When the first parameter is matched and has a value, reject is triggered, and resolve is triggered in other cases. A simple example code:

function util (func) {
  return (...arg) => new Promise((resolve, reject) => {
    func(...arg, (err, arg) => {
      if (err) reject(err)
      else resolve(arg)
    })
  })
}

Calling the tool function returns an anonymous function, and the anonymous function receives the parameters of the original function.

After the anonymous function is called, it calls the real function based on these parameters and splices a callback for processing the result.

Detects that err has a value, triggers reject, and triggers resolve in other cases

resolve can only pass in one parameter, so there is no need to use...arg in the callback to get all returns Value

Conventional usage

Take an example from the official documentation

const { promisify } = require('util')
const fs = require('fs')

const statAsync = promisify(fs.stat)

statAsync('.').then(stats => {
  // 拿到了正确的数据
}, err => {
  // 出现了异常
})

and because it is Promise, we can Use await to further simplify the code:

const { promisify } = require('util')
const fs = require('fs')

const statAsync = promisify(fs.stat)

// 假设在 async 函数中
try {
  const stats = await statAsync('.')
  // 拿到正确结果
} catch (e) {
  // 出现异常
}

usage is not much different from other tools. We can easily convert the callback into Promise and then apply it in new projects.

Customized Promise

There are some scenarios where promisify cannot be used directly for conversion. There are roughly two situations:

1. A callback function that does not follow the Error first callback convention

2. A callback function that returns multiple parameters

The first one. If we do not follow our convention, it is likely to cause Misjudgment of reject and no correct feedback.
As for the second item, it is because Promise.resolve can only receive one parameter, and the extra parameters will be ignored.

So in order to achieve the correct results, we may need to manually implement the corresponding Promise function, but after implementing it ourselves, we cannot ensure that the user will not call promisify for your function.

So, util.promisify also provides a Symbol type key, util.promisify.custom.

Everyone who knows the Symbol type should know that it is a unique value. Here util.prosimify is used to specify the customized Promise result. The usage method is as follows:

const { promisify } = require('util')
// 比如我们有一个对象,提供了一个返回多个参数的回调版本的函数
const obj = {
  getData (callback) {
    callback(null, 'Niko', 18) // 返回两个参数,姓名和年龄
  }
}

// 这时使用promisify肯定是不行的
// 因为Promise.resolve只接收一个参数,所以我们只会得到 Niko

promisify(obj.getData)().then(console.log) // Niko

// 所以我们需要使用 promisify.custom 来自定义处理方式

obj.getData[promisify.custom] = async () => ({ name: 'Niko', age: 18 })

// 当然了,这是一个曲线救国的方式,无论如何 Promise 不会返回多个参数过来的
promisify(obj.getData)().then(console.log) // { name: 'Niko', age: 18 }

About Why Promise can't resolve multiple values? I have a bold idea, a reason that has not been verified and forced to explain: if it can resolve multiple values, how do you ask the async function to return (just read this sentence for fun, don't Seriously)
But it should be related to return, because Promise can be called in a chain. After executing then in each Promise, its return value will be used as the value of a new Promise object resolve. There is no way to return in JavaScript. Multiple parameters, so even if the first Promise can return multiple parameters, they will be lost as long as they are processed by return.

In use, it is very simple to add promisify.custom to the function that may be called promisify. Just handle it accordingly.
When subsequent code calls promisify, it will be judged:

If the target function has the promisify.custom attribute, its type will be judged:

If it is not an executable function, throw Exception occurs

If it is an executable function, its corresponding function will be returned directly

If the target function does not have the corresponding attribute, the corresponding processing function will be generated according to the convention of Error first callback and then returned

After adding this custom attribute, you no longer have to worry about the user calling promisify for your function.

And it can be verified that the function assigned to custom and the function address returned by promisify are in the same place:

obj.getData[promisify.custom] = async () => ({ name: 'Niko', age: 18 })

// 上边的赋值为 async 函数也可以改为普通函数,只要保证这个普通函数会返回 Promise 实例即可
// 这两种方式与上边的 async 都是完全相等的

obj.getData[promisify.custom] = () => Promise.resolve({ name: 'Niko', age: 18 })
obj.getData[promisify.custom] = () => new Promise(resolve({ name: 'Niko', age: 18 }))

console.log(obj.getData[promisify.custom] === promisify(obj.getData)) // true

Some built-in custom processing

In some built-in packages, you can also find traces of promisify.custom. For example, the most commonly used child_process.exec has built-in promisify.custom processing:

const { exec } = require('child_process')
const { promisify } = require('util')

console.log(typeof exec[promisify.custom]) // function

Because as mentioned in the previous example In order to save the country, the official method is to use the parameter name in the function signature as the key, and store all its parameters in an Object object for return. For example, the return value of child_process.exec will include two stdout, except error. and stderr, one is the correct output after the command is executed, and the other is the error output after the command is executed:

promisify(exec)('ls').then(console.log)
// -> { stdout: 'XXX', stderr: '' }

Or we deliberately enter some wrong commands. Of course, this can only be captured under the catch module. When a normal command is executed, stderr will be an empty string:

promisify(exec)('lss').then(console.log, console.error)
// -> { ..., stdout: '', stderr: 'lss: command not found' }

包括像setTimeoutsetImmediate也都实现了对应的promisify.custom。  
之前为了实现sleep的操作,还手动使用Promise封装了setTimeout

const sleep = promisify(setTimeout)

console.log(new Date())

await sleep(1000)

console.log(new Date())

内置的 promisify 转换后函数

如果你的Node版本使用10.x以上的,还可以从很多内置的模块中找到类似.promises的子模块,这里边包含了该模块中常用的回调函数的Promise版本(都是async函数),无需再手动进行promisify转换了。

而且我本人觉得这是一个很好的指引方向,因为之前的工具实现,有的选择直接覆盖原有函数,有的则是在原有函数名后边增加Async进行区分,官方的这种在模块中单独引入一个子模块,在里边实现Promise版本的函数,其实这个在使用上是很方便的,就拿fs模块进行举例:

// 之前引入一些 fs 相关的 API 是这样做的
const { readFile, stat } = require('fs')

// 而现在可以很简单的改为
const { readFile, stat } = require('fs').promises
// 或者
const { promises: { readFile, stat } } = require('fs')

后边要做的就是将调用promisify相关的代码删掉即可,对于其他使用API的代码来讲,这个改动是无感知的。  
所以如果你的node版本够高的话,可以在使用内置模块之前先去翻看文档,有没有对应的promises支持,如果有实现的话,就可以直接使用。

promisify 的一些注意事项

  1. 一定要符合Error first callback的约定

  2. 不能返回多个参数

  3. 注意进行转换的函数是否包含this的引用

前两个问题,使用前边提到的promisify.custom都可以解决掉。 

但是第三项可能会在某些情况下被我们所忽视,这并不是promisify独有的问题,就一个很简单的例子:

const obj = {
  name: 'Niko',
  getName () {
    return this.name
  }
}

obj.getName() // Niko

const func = obj.getName

func() // undefined

类似的,如果我们在进行Promise转换的时候,也是类似这样的操作,那么可能会导致生成后的函数this指向出现问题。  
修复这样的问题有两种途径:

  1. 使用箭头函数,也是推荐的做法

  2. 在调用promisify之前使用bind绑定对应的this

不过这样的问题也是建立在promisify转换后的函数被赋值给其他变量的情况下会发生。  
如果是类似这样的代码,那么完全不必担心this指向的问题:

const obj = {
  name: 'Niko',
  getName (callback) {
    callback(null, this.name)
  }
}

// 这样的操作是不需要担心 this 指向问题的
obj.XXX = promisify(obj.getName)

// 如果赋值给了其他变量,那么这里就需要注意 this 的指向了
const func = promisify(obj.getName) // 错误的 this

小结

个人认为Promise作为当代javaScript异步编程中最核心的一部分,了解如何将老旧代码转换为Promise是一件很有意思的事儿。 

而我去了解官方的这个工具,原因是在搜索Redis相关的Promise版本时看到了这个readme:This package is no longer maintained. node_redis now includes support for promises in core, so this is no longer needed.

然后跳到了node_redis里边的实现方案,里边提到了util.promisify,遂抓过来研究了一下,感觉还挺有意思,总结了下分享给大家。

The above is the detailed content of Explanation of related content of util.promisify. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor