This is what you did when you called the promise:
sumar(1,2).then((result) => {
console.log(result)
return multiplicar(result)
.then(resp => {
console.log(resp)
return verificar(resp)
.then(resultVerificado => {
console.log(resultVerificado)
})
})
})
In fact, you are not applying the concept properly; just what it's about avoiding is that kind of nesting and indentation that you do when you make the promise.
I also do not understand why you created promises in each of the functions.
On the other hand, I would prefer to encapsulate everything in a class with static methods to give it order so I'll give you an example with class Calc
and 4 methods.
3 with the required processes where, who has the promise is only the method sumar
and I add a method triggerAll()
to be able to execute all the chaining. That chain is just one of the great benefits of promises that is very different from the -anidation you did.
I use 2 input and one button, then I throw the results to <span>
tags.
The lines where the data is sent to the sun are only to show the result but are not necessary because obviously in a real application it would only be waiting for a result to use it in something. if we remove this and also assign the results and return everything by return
you will notice that the code is reduced too much and with the benefit that that chain ( in the method triggerAl()
) of the promise it becomes much more readable.
I did not validate the fields, so if you do not fill them out, it will throw you a NaN
but it will show you by console the error that captures the promise.
I hope it will be useful and you tell me if it served you.
Your exercise would look something like this:
// obtengo los elementos del Dom con los que voy a interactuar
const num1 = document.querySelector('#num1'),
num2 = document.querySelector('#num2'),
clear = document.querySelector('#btnClear'),
result = document.querySelector('#btnResult'),
txtAdd = document.querySelector('#s'),
txtMult = document.querySelector('#m'),
txtCheck = document.querySelector('#v');
// ----------------------------------------
// Clase que contiene los métodos estáticos
// sumar, multiplicar y verificar y él método
// [triggerAll] que es el que aplica el "Promise"
// ----------------------------------------
class Calc {
static sumar(a, b) {
return new Promise((resolve, reject) => {
a && b ? resolve(a + b) : reject('Error: Falta un número !');
txtAdd.innerHTML = (a+b); // sólo para comprobar resultado
});
}
static multiplicar(result) {
result *= 5
txtMult.innerHTML = result // sólo para comprobar resultado
return result;
}
static verificar(newResult) {
let msg = newResult > 10 ? 'El resultado es Mayor que 10'
: 'El Resultado es igual o menor que 10';
txtCheck.innerHTML = msg; // sólo para comprobar resultado
}
// Método que aplica todo el [Promise]
static triggerAll(a,b){
Calc.sumar(a,b)
.then(result => Calc.multiplicar(result))
.then(newResult => Calc.verificar(newResult))
.catch(error => console.error(error));
}
} // Fin de la clase Calculo
// Evento del botón
result.addEventListener('click', () => {
Calc.triggerAll(parseInt(num1.value), parseInt(num2.value));
});
/* un poquito de **CSS** */
span{
color: green;
font-size: 1.2rem;
}
<div class="input">
<label for="num1">Numero 1</label>
<input type="number" id="num1" name="num1">
</div>
<div class="input">
<label for="num2">Numero 2</label>
<input type="number" id="num2" name="num2">
</div>
<button id="btnResult">Resultado</button>
<p>Resultado de la suma :<span id="s"></span> </p>
<p>Resultado de la Multiplicación por 5 :<span id="m"></span> </p>
<p>Resultado de la Verificación :<span id="v"></span> </p>