sterlingandcooper
sterlingandcooper

Reputation: 1

Javascript. Transform synchronous function as asynchronous using callbacks, promises, async/await, generators

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

Upvotes: 0

Views: 1276

Answers (1)

Scott Rudiger
Scott Rudiger

Reputation: 1300

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);

Upvotes: 0

Related Questions