I am trying to learn JS Promise. I have the following function which returns either the sum or difference of two numbers depending on the 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 tried to use Promise to achieve the same thing with the following codes.
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);
});
Would it be possible to pass multiple arguments into Promise.resolve instead of an array?