I am trying to learn promises in JS. I have a function that computes the sum or difference of two numbers depending on operation provided by the user.
function compute(firstNum, secondNum, operation) {
let result = null;
operation === "+"
? (result = firstNum + secondNum)
: operation === "-"
? (result = firstNum - secondNum)
: console.log("operation not supported");
return result;
}
I am trying to define a function that returns a promise which does essentially the same thing as the compute function above.
let operators = {
"+": function (a, b) {
console.log(a + b);
},
"-": function (a, b) {
console.log(a - b);
},
};
function calculate(firstNum, secondNum, operation) {
return new Promise((resolve, reject) => {
if (operation === "+" || operation === "-")
resolve([firstNum, secondNum, operation]);
else reject(new Error("operation not supported"));
});
}
calculate(5, 51, "-")
.then((returnedArr) => {
let answer = operators[returnedArr[2]](returnedArr[0], returnedArr[1]);
})
.catch((err) => {
console.log(err);
});
Is it possible to pass more than one argument to resolve() inside a promise?