Reputation: 539
i´m triying yo learn to use promises to make validations of mysql. This is my code.
//main.js
var valida= require('./modulos/validaciones');
var valor=valida.userP(data).then((rows,error)=>{
console.log(rows);
});
console.log(valor);
//valida.js
var mysql= require('mysql');
exports.userP= (data)=>{
return promise = new Promise(resolve,reject)=>{
conection.query(data.valida_user,(error,rows)=>{
if (error) reject(error);
console.log("Entra en validacion");
console.log(rows);
resolve(rows);
});
};
};
But when i run the code, console show me this return promise = _new_ Promise(resolve,reject)=>{
SyntaxError: Unexpected token new
I am using nodejs 8.11
Upvotes: 1
Views: 742
Reputation: 707238
Change your code to this:
exports.userP = (data) => {
return new Promise((resolve, reject) => {
conection.query(data.valida_user, (error, rows) => {
if (error) return reject(error);
console.log("Entra en validacion");
console.log(rows);
resolve(rows);
});
});
};
There were multiple mistakes:
The variable promise
is not defined anywhere and is not needed. You can just return the promise directly.
You were missing parens around (resolve, reject)
to make it a proper arrow function declaration with multiple arguments.
You need a return
before your reject()
so processing will not continue.
You were missing a closing paren to close the new Promise()
.
Upvotes: 2
Reputation: 21
This sould do the trick, basically this line:
return promise = new Promise(resolve,reject)=>{
For this:
return new Promise ((resolve,reject) => {
Full code below:
//main.js
var valida= require('./modulos/validaciones');
var valor=valida.userP(data).then((rows,error)=>{
console.log(rows);
});
console.log(valor);
//valida.js
var mysql= require('mysql');
exports.userP= (data)=>{
return new Promise ((resolve,reject) => {
conection.query(data.valida_user,(error,rows)=>{
if (error) reject(error);
console.log("Entra en validacion");
console.log(rows);
resolve(rows);
});
});
};
Upvotes: 1