简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM