我正试图创建一个函数,但当第一个函数是异步函数时,它会抛出错误function1(...) is not a function,然而,如果我将异步函数作为最后一个函数传递,它工作得很好.

有人能告诉我为什么会发生这种事吗?以及如何正确地制作以异步函数开头的Curry函数?

感谢所有抽出时间的人.


//This one is throwing the error: function1(...) is not a function
async function function1(path) {
 const fetchedElement = await fetchElement(path);
//(...)
  return (msg) => {
    console.log(msg);
  };
}

function1('somepath.html')('my message');

//This one works fine, properly returning other function
function function2(path) {
  return async (msg) => {
    const fetchedElement = await fetchElement(path);
  //(...)
    console.log(msg);
  };
}
function2('somepath.html')('my message');

推荐答案

这取决于何时需要完成异步工作.如果您希望当前进程执行异步工作,则不能同步调用当前函数:

curryingFunction(paramA)(paramB)
                        ^ assumes curryingFunction is synchronous

取而代之的是,使用调用方的两个语句,一个用于等待当前调用,另一个用于调用...

const fetch = path => new Promise(resolve => setTimeout(() => {
  console.log('fetched ' + path)
  resolve()
}, 1000));

async function curryingFunction(path) {
  const fetchedElement = await fetch(path);
  return message => {
    console.log(message);
  }
}

async function someCaller() {
  // await to get a curried function, then invoke it
  let curried = await curryingFunction('some_path');
  curried('some message');
}

someCaller()

另一方面,您可能不需要为了获得Currate函数而执行异步工作.您可能不需要.在这种情况下,您可以使当前函数同步,但让它返回一个执行异步工作的异步函数.

因此,您将能够使用您可能习惯使用的fn()()语法...

const fetch = path => new Promise(resolve => setTimeout(() => {
  console.log('fetched ' + path)
  resolve()
}, 1000));

function curryingFunction(path) {
  return async (message) => {
    const fetchedElement = await fetch(path);
    console.log(message);
  }
}

async function someCaller() {
  // here we can use the fn()() syntax that we're accustomed to
  await curryingFunction('some path')('some message')
}

someCaller()

Javascript相关问答推荐

从PWA中的内部存储读取文件

如何将连续的十六进制字符串拆分为以空间分隔的十六进制块,每个十六进制块包含32个二元组?

如何在RTK上设置轮询,每24小时

网页自检测外部元素无法加载

无法从NextJS组件传递函数作为参数'

用于编辑CSS样式的Java脚本

如何在文本字段中输入变量?

WhatsApp Cloud API上载问题:由于MIME类型不正确而导致接收&Quot;INVALID_REQUEST";错误

回溯替代方式

如何利用CSS中的隐藏元素实现平滑扩展和防止网格行间隙

Node.js错误: node 不可单击或不是元素

用于测试其方法和构造函数的导出/导入类

表单数据中未定义的数组键

在HTML中使用meta标记来指定定制元数据以用于使用JavaScript进行检索是不是一个坏主意?

如何格式化API的响应

如何从嵌套的json中获取最大值

如何在preLoad()中自定义p5.js默认加载动画?

如何使用Angular JS双击按钮

Html/JS:如何在脚本执行前阻止呈现?

我怎么才能拿到幼风登录?