I'm starting with Promises and I have the following code:
let datos = ["Jorge Balsamo","@SoyDalto","Curso de Javascript"];
function validarNombre(){
return new Promise((resolve,reject)=>{
if(datos[0]!="Jorge Balsamo") reject("El nombre indicado no es el correcto");
else resolve("El nombre es correcto");
})
}
function validarInstagram(){
return new Promise((resolve,reject)=>{
if(datos[1].includes("@") && datos[1]!=undefined) resolve("Instagram validado correctamente");
else reject("El IG es invalido o es undefined");
})
}
function validarCurso(){
return new Promise((resolve,reject)=>{
if(datos[2]!="Curso de Javascript") reject("El curso indicado no es el correcto");
else resolve("El nombre del curso es correcto");
})
}
My intention was to chain Promises to be able to catch the errors with a single catch but I couldn't and I had to do them one by one
validarNombre().then(validarInstagram().catch((err)=>{
console.log(err);
})).then(validarCurso().catch((err)=>{
console.log(err);
}))
Basically what I want to do is chain the Promises to at the end add a catch that captures and displays the errors of any of the 3 functions in the console. That's supposedly the advantage of using promises versus just using callbacks, but I can't implement chaining correctly (I'm just starting out sorry).
In response to your question
First of all: what you 're already doing is chaining promises , including promise results in the .then() block of a promise is chaining, so in principle that's correct. You will execute each promise sequentially each time one resolves.
Perhaps what you want to do is easier if you put it in async / await syntax.
I give you an example.
An alternative
You say you want to handle all three promises with a single then/catch
You really don't need to chain promises at all. In this particular case, in fact, the promises you define do not depend on each other.
For this (I repeat, when your promises don't depend on each other) you could use Promise.allSetled() , which executes all the promises you have and will return an Array with its result.
You could then test if any of the promises have been rejected and transform the error codes as you see fit.
I hope it helps you understand a little better how to work with multiple promises in parallel and in sequence.