Eleazar Ortega
Eleazar Ortega

Reputation: 539

Error with Promises in NodeJs

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

Answers (2)

jfriend00
jfriend00

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:

  1. The variable promise is not defined anywhere and is not needed. You can just return the promise directly.

  2. You were missing parens around (resolve, reject) to make it a proper arrow function declaration with multiple arguments.

  3. You need a return before your reject() so processing will not continue.

  4. You were missing a closing paren to close the new Promise().

Upvotes: 2

Felipe Vargas
Felipe Vargas

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

Related Questions