How can I use the promises nested in this case? NodeJs

0

I'm doing a code that makes 3 sequential validations, and I'm using promises, however I understand that there is a structure of promises sequential, but I do not understand how to use it in this case.

valida.user(data).then((rows)=>{
	validaciones.user=rows;
})
valida.mail(data).then((rows)=>{
	validaciones.mail=rows;
})
valida.ced(data).then((rows)=>{
	validaciones.ced=rows;
	console.log(validaciones);
})

This brings me back ...

{ user: false, mail: false, ced: false }

... After having validated that there are no records in the database with that same "user", "mail" or "ced"

But I want to implement it this way =

valida.user(data).then((rows)=>{
	validaciones.user=rows;
}).then(valida.mail(data)).then((rows)=>{
	validaciones.mail=rows;
}).then(valida.ced(data)).then((rows)=>{
	validaciones.ced=rows;
	console.log("Resultado :"+validaciones);
});
However this returns me
Resultado :[object Object]

My question is what is the correct structure to use the nested .then

    
asked by Eleazar Ortega 10.11.2017 в 00:58
source

3 answers

1

In your case you can see how are multiple methods of valida , you can do the following, returning the promise of your call to any method of valida within then allows you to reuse .then and pass the value already resolved, in this case you called it rows .

Note: I do not know what content has data but I leave it to you.

valida.user(data).then((rows) => {
    validaciones.user = rows;
    return valida.mail(data);
}).then((rows) => {
    validaciones.mail = rows;
    return valida.ced(data);
}).then((rows) => {
    validaciones.ced = rows;
    console.log("Resultado :" + validaciones);
});

or you can use Promise.all :

Promise.all([
    valida.user(data),
    valida.mail(data),
    valida.ced(data)
]).then((rows) => {
    // rows es un array que contiene todos los valores resueltos. Ej.
    // rows[0] => rows de valida.user();
    // rows[1] => rows de valida.mail();
    // rows[2] => rows de valida.ced();
});
    
answered by 10.11.2017 в 01:25
0

I recommend you look at async and await, the new ES7. If you want to learn a little more, in this article I explain it more in detail. link

    
answered by 10.11.2017 в 02:15
0

Validations is an object. If you concatenate it with the string "Result:", it will always return [object Object]

You just need to log it in as

console.log("Resultado :",validaciones);

from your second example.

(I assume that validaciones is a variable declared before the chain of promises).

    
answered by 10.11.2017 в 16:28