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.
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.
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.
Converts callback-based functions to Promises, using a boilerplate callback function.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With