简体   繁体   English

的JavaScript。 使用回调,promises,async / await,generator将同步函数转换为异步

[英]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 后者使用回调更改为异步,如下所示: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 以及如何使用async / await,generator,Promises进行转换

Here's one way you could refactor your original code to async/await (without using callbacks): 这里有一种方法可以将原始代码重构为async / await(不使用回调):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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