javascript - Simple Callback to Promise Conversion - Stack Overflow

PHOTO EMBED

Tue Feb 22 2022 14:02:19 GMT+0000 (Coordinated Universal Time)

Saved by @dickosmad #javascript #promises

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
content_copyCOPY

https://stackoverflow.com/questions/65599362/simple-callback-to-promise-conversion