Home  >  Article  >  Web Front-end  >  Explanation of related content of util.promisify

Explanation of related content of util.promisify

不言
不言forward
2018-10-18 14:19:262155browse

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.com. If there is any infringement, please contact admin@php.cn delete