Search code examples
javascriptcallbackes6-promise

Simple Callback to Promise Conversion


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.


Solution

  • 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).