Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs util.promisify is not a function

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:

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);

I´m new programming but I'm trying to learn.

like image 672
Eleazar Ortega Avatar asked Sep 28 '17 19:09

Eleazar Ortega


People also ask

What is util Promisify in node JS?

The util. promisify() method basically takes a function as an input that follows the common Node. js callback style, i.e., with a (err, value) and returns a version of the same that returns a promise instead of a callback.

How do you Promisify a function in Javascript?

function promisify(f) { return function (... args) { // return a wrapper-function (*) return new Promise((resolve, reject) => { function callback(err, result) { // our custom callback for f (**) if (err) { reject(err); } else { resolve(result); } } args.

What is es6 Promisify?

Converts callback-based functions to Promises, using a boilerplate callback function.

How do you Promisify callbacks?

promisify() function is not available. The idea is to create a new Promise object that wraps around the callback function. If the callback function returns an error, we reject the Promise with the error. If the callback function returns non-error output, we resolve the Promise with the output.


2 Answers

util.promisify is a part of Node 8.X version. But you can still have a polyfill for the older version of Node.

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.promisify 

Now 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); 

Quoted from https://grizzlybit.info/blog/nodejs-util-promisify

like image 193
zubair1024 Avatar answered Sep 19 '22 15:09

zubair1024


Unless you're using Node.js 8.x this function won't be defined, that's when it was added to the core Utilities library.

As util is 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 Bluebird which has a promisify function.

like image 44
tadman Avatar answered Sep 19 '22 15:09

tadman