0

I have two functions, witch previously were designed to run synchronously.

function addOne(recievedInt) {
   ...some network requests happend...
   return recievedInt = receivedInt++;
}

and

function sum(arg1, arg2) {
   ... do some manipulations...
   return arg1 + arg2;
}

Latter both were changed to be asynchronous using callbacks and look as following: function

addOne(recievedInt, callback),  sum(arg1, arg2, callback)

Now I need to change third functions which previously was using both functions from synchronous to async passing callback to each of them.

function compute(value) {
   var c = addOne(value);
   var a = sum(value, c) + c;
   return a;
}

My best solutions was:

function compute(value) {
   return addOne(value, function(n1) {
      return sum(value, n1, function(n2) {
         return n2 + n1;
      });
   });
}

Is that is the right implementation for callback based asynchronous version? And how it can be converted using async/await, generators, Promises

  • I think the real question is **why** do these needs to become asynchronous? Do these perform **async** operations? or is it just matter of handling a **callback**? – briosheje Mar 27 '19 at 11:32
  • not sure if this is fully a dupe, but [this question](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) might have some ideas that help you – Robin Zigmond Mar 27 '19 at 11:44
  • briosheje, yes, they perform sync operations, I just didn't paste that bit. – sterlingandcooper Mar 27 '19 at 12:01
  • do they perform SYNC or **A**SYNC operations? if they perform **sync** operations, may I ask you why you need to make them **async**? Of course you can do that by simply wrapping them in promise blocks, but the question, to me, is **why** you should do that, since they are **not** async. – briosheje Mar 27 '19 at 13:24

1 Answers1

0

Here's one way you could refactor your original code to async/await (without using callbacks):

const fakeAsyncStuff = () => Promise.resolve();

const addOne = async n => {
  await fakeAsyncStuff();
  return n + 1;
};

const sum = async (a, b) => {
  await fakeAsyncStuff();
  return a + b;
};

const compute = async value => {
  const c = await addOne(value);
  const a = await sum(value, c);
  return c + a;
};

compute(1).then(console.log);
Scott Rudiger
  • 1,224
  • 12
  • 16