Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - Simple Callback to Promise Conversion


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...