You can just convert the functions into async functions/promises.
Some good documentation about that can be found here .
But I guess you also want to simulate some delay. So I added additional function for that (it might help with understanding).
const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
const sumWithDelay = async (a, b) => {
console.log("Delay started")
await sleep(3000)
console.log("Delay ended")
return a + b;
}
const sum = async (a, b) => {
return a + b;
}
const mul = async (a, b) => {
return a * b;
}
let dne = async function() {
return 'it does not exist';
};
let doCalculation = function(route) {
switch (route) {
case 'sum':
return sum;
case 'sumWithDelay':
return sumWithDelay;
case 'mul':
return mul;
default:
return dne;
}
};
doCalculation('sumWithDelay')(2, 2).then(res => console.log(res)); //4
doCalculation('sum')(3, 4).then(res => console.log(res)); // 7
doCalculation('mul')(3, 4).then(res => console.log(res)); // 12
doCalculation('dne')(3, 4).then(res => console.log(res)); // it does not exist
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…