javascript - 将函数转换为异步函数而不重新定义
问题描述
java - 如何在java脚本中将函数更改为异步函数没有重新定义函数或编辑代码并附async
加到函数语句
f = () => 0;
console.log(f); // [Function (anonymous)]
console.log(asyncify(f)); // [AsyncFunction (anonymous)]
console.log(f()); // 0
console.log(asyncify(f)()); // Promise { 0 }
asyncify(f)().then(console.log) // 0
问为什么被禁止
解决方案
查看asyncify
函数,我们看到它传递了一个函数f
,并且还必须返回一个异步函数。所以它有以下形式:
accept function `f` ----> return Async Function
上面的定义可以用箭头函数来写:
const asyncify = f => (async () => {})
上面,我们看到(async () => {})
的是正在返回的 Async 函数,并且该 async 函数当前有一个空的 body {}
。我们也可以删除它周围的括号,因为这不是必需的,为了清楚起见,我主要包括它。查看您所追求的结果,您希望从上述异步函数返回一个 Promise,该函数解析为f()
. 可以通过显式返回一个解析为您的值的 Promise 来实现这一点:
const asyncify = f => async () => new Promise(resolve => resolve(f()))
但是上面的代码有一些冗余。一个async
函数将自动返回一个 Promise,它解析为从它返回的值。所以它可以写成:
const asyncify = f => async () => f();
这将得到您所追求的结果。但是,我们忽略了f()
可能需要将参数传递给它的事实。为了解决这个问题,我们可以将一些参数传递给我们的async
函数,并将它们转发给我们的f
函数以使用。要指定可变数量的参数,我们可以使用剩余参数:
const asyncify = f => async (...args) => f(...args);
有了这一切,您将在 Node 中获得以下输出:
const asyncify = f => async (...args) => f(...args);
const f = () => 0;
console.log(f); // [Function: f]
console.log(asyncify(f)); // [AsyncFunction (anonymous)]
console.log(f()); // 0
console.log(asyncify(f)()); // Promise { 0 }
asyncify(f)().then(console.log) // 0
const asyncify = f => async (...args) => f(...args);
const f = () => 0;
console.log(f); // [Function (anonymous)]
console.log(asyncify(f)); // [AsyncFunction (anonymous)]
console.log(f()); // 0
console.log(asyncify(f)()); // Promise { 0 }
asyncify(f)().then(console.log) // 0
推荐阅读
- php - 1我尝试构建产品表单但记录无法插入数据库
- javascript - 我如何创建类别,例如如何?什么时候?为什么?对于某些视频会显示的大量文本?
- java - 如何使用'MOCKITO_CORE when'在junit测试用例中传递void返回类型
- python - 蛮力法算法python
- javascript - 如何找到 2 个动态创建的 div 类
- android - Retrofit/Gson 将 \n 添加到大字符串中
- javascript - 通过 AJAX 将值传递给控制器,无需使用 Thymeleaf 进行任何用户输入
- flutter - 无法解析配置“:classpath”的所有工件。无法解析 org.jetbrains.kotlin:kotlin-reflect:1.2.71
- node.js - 我如何在node.js中使用多个参数rest api
- laravel - 阻止特定角色的用户访问路由