Javascript NodeJs util.promisify 不是一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46476741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJs util.promisify is not a function
提问by Eleazar Ortega
I'm trying to promisify a mysql function but when I run it the console shows this error util.Promisify is not a function. This is my code:
我正在尝试 promisify 一个 mysql 函数,但是当我运行它时,控制台显示此错误util.Promisify is not a function。这是我的代码:
var util= require('util');
var mysql= require('mysql');
var conection=mysql.createConnection({
host:'localhost',
user:'root',
password:'616897',
database:'proyect'
});
var query = util.promisify(conection.query);
query(data.valida_user).then((rows)=>{
console.log(rows);
}).catch((error)=>{
console.log(error);
})
The same error if
var query = util.promisify(mysql.query);
同样的错误如果
var query = util.promisify(mysql.query);
I′m new programming but I'm trying to learn.
我是新编程,但我正在努力学习。
回答by zubair1024
util.promisify is a part of Node 8.X version. But you can still have a polyfill for the older version of Node.
util.promisify 是 Node 8.X 版本的一部分。但是您仍然可以为旧版本的 Node.js 使用 polyfill。
A polyfill is available to take care of the older version of node servers you'll be running your application on. It can be installed via npm in the following manner:
npm install util.promisifyNow you can patch module utl on older versions of Node
const util = require('util'); require('util.promisify').shim(); const fs = require('fs'); const readFileAsync = util.promisify(fs.readFile);
一个 polyfill 可用于处理您将在其上运行应用程序的旧版本节点服务器。它可以通过以下方式通过 npm 安装:
npm install util.promisify现在您可以在旧版本的 Node 上修补模块 utl
const util = require('util'); require('util.promisify').shim(); const fs = require('fs'); const readFileAsync = util.promisify(fs.readFile);
Quoted from http://grizzlybit.info/2017/09/29/Node-JS-8-Util-Promisify/
引自http://grizzlybit.info/2017/09/29/Node-JS-8-Util-Promisify/
回答by tadman
Unless you're using Node.js 8.x this function won't be defined, that's when it was addedto the core Utilitieslibrary.
除非您使用的是 Node.js 8.x,否则不会定义此函数,那时它将被添加到核心Utilities库中。
As utilis a core Node.js library, you shouldn't have to install it. If you're using Node.js 6.x then use a library like Bluebirdwhich has a promisifyfunction.
作为util核心 Node.js 库,您不必安装它。如果您使用的是 Node.js 6.x,那么请使用像Bluebird这样具有promisify函数的库。
回答by richb-hanover
Other people have spoken to the solution, but here is another source of this error:
其他人已经讨论过该解决方案,但这是此错误的另一个来源:
There's a NPM package es6-promisifythat can also give the error message TypeError: promisify is not a function. (That's why I got to this question.)
有一个 NPM 包es6-promisify也可以给出错误消息TypeError: promisify is not a function。(这就是我问这个问题的原因。)
Version 5.0.0 of es6-promisifiy needed
const promisify = require("es6-promisify");then you'd useresult = promisify( ... );Version 6.0.0 had a change of API, and the declaration changed to
const { promisify } = require("es6-promisify");
需要 es6-promisify 的 5.0.0 版,
const promisify = require("es6-promisify");然后你会使用result = promisify( ... );6.0.0 版本 API 发生了变化,声明改为
const { promisify } = require("es6-promisify");
回答by Shl
You can promise it by yourself if you want:
const promisify = f => (...args) => new Promise((a,b)=>f(...args, (err, res) => err ? b(err) : a(res)));
如果您愿意,您可以自己承诺:
const promisify = f => (...args) => new Promise((a,b)=>f(...args, (err, res) => err ? b(err) : a(res)));
回答by Seph Cordovano
Util is included from Node 8.x on so if you can update node I'd do that.
Util 包含在 Node 8.x 中,因此如果您可以更新节点,我会这样做。
回答by user2080851
The following example should work for you:
以下示例应该适合您:
async () => {
const connection = await (util.promisify(pool.getConnection).bind(pool))();
const fn2 = util.promisify(connection.query).bind(connection);
const rows = await fn2('SELECT col1, col2 FROM Users WHERE email = ?', [email]);
connection.release();
return rows;
}
This example uses the standard MySQL module for Node.js. And the util.promisify is the built-in utility of Node.js. Node 8 is used.
此示例使用 Node.js 的标准 MySQL 模块。util.promisify 是 Node.js 的内置实用程序。使用节点 8。
The code is wrapped into an async function. Within it on the first line the callback function ‘pool.getConnection' is converted into promises and called instantly with the additional ‘await' statement. This creates a sequence of the async function and returns a value (a connection) instead of a function or promises. The next line does the same for the ‘conection.query', but splits the code into two statements for the sake of simplicity. Finally the function returns the result of the query like any synchronous function.
代码被包装成一个异步函数。在它的第一行中,回调函数“pool.getConnection”被转换为承诺并立即使用附加的“await”语句调用。这将创建一个异步函数序列并返回一个值(一个连接)而不是一个函数或承诺。下一行对 'conection.query' 执行相同的操作,但为了简单起见,将代码拆分为两个语句。最后,该函数像任何同步函数一样返回查询结果。
回答by HMR
Here is an implementation of promisify:
这是promisify的一个实现:
var promisify = function(fn) {
return function(){
var args = [].slice.apply(arguments);
return new Promise(
function(resolve,reject){
fn.apply(
null,
args.concat([
function(){
var results = [].slice.apply(arguments);
(results[0])//first argument of callback is error
? reject(results[0])//reject with error
: resolve(results.slice(1,results.length))//resolve with result(s)
}
])
)
}
);
}
};
//some object that has async functions using callbacks
// and using 'this' as invoking object
var callbackApi = {
name:"callback api",
age:22,
asyncFunction:function(arg1,arg2,callback){
setTimeout(
function(){callback(null,arg1,arg2,this.name,this.age);}.bind(this),
10
)
}
}
//my object that will use the api functions with promisify
// and using 'this' as invoking object
var myObject = {
connection:"connection",
doSomething:function(arg){
var asyncFnAsPromise =
//make sure to bind asyncFunction to callbackApi
promisify(callbackApi.asyncFunction.bind(callbackApi));
//return promise created with result promisified callback api
return asyncFnAsPromise(this.connection,arg)
}
}
myObject.doSomething(44)
.then(
resolve=>console.log("resolve:",resolve)
);
回答by Keyvan
If you have a webpack/babelsetup, you can use babel-plugin-transform-util-promisify. It allows you to use util.promisifyin node versions < 8. Also very useful if you are targeting node versions >= 8 but want to keep backward compatibility for lower versions.
如果你有webpack/ babel设置,你可以使用babel-plugin-transform-util-promisify. 它允许您util.promisify在节点版本 < 8 中使用。如果您的目标节点版本 >= 8 但希望保持较低版本的向后兼容性,这也非常有用。
The plugin transforms code written in the following two formats:
该插件转换以以下两种格式编写的代码:
const { promisify } = require('util');
and
和
import { promisify } from 'util';
You would need to setup the plugin in your .babelrc:
您需要在您的.babelrc:
{
"plugins": [
"transform-util-promisify"
],
"presets": [
["env", {
"targets": {
"node": "current"
}
}]
]
}
The plugin transforms importand requireto a function declarationfor node versions < 8. It automatically detects version >= 8 and uses native util.promisifyin those cases.
插件变换import和require到一个函数声明节点版本<8.自动检测版本> = 8和用途天然util.promisify于这些情况。
DisclosureI'm author and maintainer of babel-plugin-transform-util-promisify
披露我是 babel-plugin-transform-util-promisify 的作者和维护者
回答by hoogw
Share my working example:
分享我的工作示例:
I use this Promisified MySQL middleware for Node.js
我将这个Promisified MySQL 中间件用于 Node.js
here is my database.js
这是我的 database.js
var mysql = require('mysql');
// node -v must > 8.x
var util = require('util');
// !!!!! for node version < 8.x only !!!!!
// npm install util.promisify
//require('util.promisify').shim();
// -v < 8.x has problem with async await so upgrade -v to v9.6.1 for this to work.
// connection pool https://github.com/mysqljs/mysql [1]
var pool = mysql.createPool({
connectionLimit : process.env.mysql_connection_pool_Limit, // default:10
host : process.env.mysql_host,
user : process.env.mysql_user,
password : process.env.mysql_password,
database : process.env.mysql_database
})
// Ping database to check for common exception errors.
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
}
if (connection) connection.release()
return
})
// Promisify for Node.js async/await.
pool.query = util.promisify(pool.query)
module.exports = pool
You must upgrade node -v > 8.x
您必须升级 node -v > 8.x
you must use async function to be able to use await.
您必须使用 async 函数才能使用 await。
example:
例子:
var pool = require('./database')
// node -v must > 8.x, --> async / await
router.get('/:template', async function(req, res, next)
{
...
try {
var _sql_rest_url = 'SELECT * FROM arcgis_viewer.rest_url WHERE id='+ _url_id;
var rows = await pool.query(_sql_rest_url)
_url = rows[0].rest_url // first record, property name is 'rest_url'
if (_center_lat == null) {_center_lat = rows[0].center_lat }
if (_center_long == null) {_center_long= rows[0].center_long }
if (_center_zoom == null) {_center_zoom= rows[0].center_zoom }
_place = rows[0].place
} catch(err) {
throw new Error(err)
}

