-5

I have a simple callback example (more like pseudo-code) where values are summed up or multiplied based on the first function parameter.
This is not like a real-life example. Imagine that the task/calculation inside of functions takes some time (like for e.g. calculating the number of stars in the universe). But if we put this aside, the pattern/template with callback looks like this: 

let sum = function(a, b) {
  return a + b;
}

let mul = function(a, b) {
    return a * b;
}

let dne = function(a, b) {
    return 'it does not exist';
}

let doCalculation = function(route) {
  switch(route) {
      case 'sum':
        return sum;
      case 'mul': 
        return mul
      default: 
        return dne
  }
}

console.log(doCalculation('sum')(3, 4)) //7

Could this be refactored with Promises in a similar way and if it could be done, could it be done simpler.

  • 5
    That's not a callback? Why do you need promises for this? – evolutionxbox Jan 06 '21 at 16:17
  • 1
    You *could* employ a resolved Promise but it would help if you would explain what motivates you to want to do something like that. – Pointy Jan 06 '21 at 16:18
  • 1
    Your example doesn't sum four values - it sums two values and ignores two. What's even the point of those functions? – JLRishe Jan 06 '21 at 16:19
  • Ok what is it then? This is just a pseudo example. Looking into promises and was wondering if case like that can be refactored into with promises. – John Allcock Jan 06 '21 at 16:20
  • 2
    Promises are tools to manage asynchronous code. There is no asynchronous code here. Involving promises would be completely pointless. – Quentin Jan 06 '21 at 16:21
  • @JohnAllcock A case like what? It's entirely unclear what purpose your functions even serve, so we can't tell you how a "case like that" would apply to promises. Promises are for dealing with asynchronous operations, and there's nothing asynchronous in your example, so they are not applicable in any way to your example. – JLRishe Jan 06 '21 at 16:23
  • @Quentin Ok imagine the 'sum' method takes some time. – John Allcock Jan 06 '21 at 16:24
  • @JohnAllcock is the calculation done in the same script or somewhere else? (Like a webworker or api) – evolutionxbox Jan 06 '21 at 16:25
  • @JohnAllcock Yes. Like I said, it's a needlessly convoluted way of summing two numbers (not four) and it's unclear what purpose it serves, even without promises. So there's no way I could possibly tell you how to do "something similar" even with promises. – JLRishe Jan 06 '21 at 16:28
  • 1
    If you have a calculation which takes an arbitrarily long time using promises won't help. The calculation will block anything else until done. Promises become useful if the calculation is done elsewhere, like in a webworker or by an API. – evolutionxbox Jan 06 '21 at 16:35
  • Possible duplicate: https://stackoverflow.com/questions/54478255/why-is-my-infinite-loop-blocking-when-it-is-in-an-async-function – Quentin Jan 06 '21 at 16:37
  • @Quentin calculations can be asynchronous. While summing might be a quick process that could easily be replaced with some more complex calculation. Also not sure why you mentioned possible duplicate. In this example, there is no indefinite loops or code which would produce a blockage. – John Allcock Jan 08 '21 at 12:23

2 Answers2

1

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

The output will be:
Delay started
7
12
it does not exist
Delay ended
4

You can see that the "sum with delay" has been executed last (after 3 sec).

Patrik Bego
  • 4,009
  • 1
  • 26
  • 24
-1

let sum = function(a, b) {
  return a + b;
};

new Promise(function(resolve, reject) {
  resolve(sum(1, 2));
}).then(function(previousSum) {
  return previousSum + sum(3, 4);
}).then(function(previousSum) {
  document.body.innerHTML = previousSum + sum(5, 6);
});
Kostas
  • 1,903
  • 1
  • 16
  • 22