首页 > 解决方案 > 将函数转换为异步函数而不重新定义

问题描述

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

问为什么被禁止

标签: javascriptnode.js

解决方案


查看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


推荐阅读