如何知道一个函数是否是asynchronous的?

我必须将函数传递给另一个函数,并将其作为callback来执行。 问题是,有时这个函数是asynchronous的,就像:

async function() { // Some async actions } 

所以我想根据它正在接收的函数的types执行await callback()callback()

有没有办法知道函数的types?

当转换为string时,本地async函数可能是可识别的:

 asyncFn[Symbol.toStringTag] === 'AsyncFunction' 

或者通过AsyncFunction构造函数:

 const AsyncFunction = (async () => {}).constructor; asyncFn instanceof AsyncFunction === true 

或者确保它不会在传送的代码中出现误报:

 (asyncFn instanceof AsyncFunction && AsyncFunction !== Function) === true 

这个问题显然是指asynchronous函数的Babel实现,asynchronous函数依赖于transform-async-to-generator来asynchronous生成函数,还可以使用transform-regenerator将生成器转换为正常函数。

asynchronous函数调用的结果是一个承诺。 根据提案 ,可能会通过承诺或非承诺await

一般来说,asynchronous函数不应该与返回promise的常规函数​​区分开来。 在这种情况下,没有办法或理由检测非本地asynchronous函数。

@rnd和@estus都是正确的。

但是要回答这个问题,你需要一个实际的工作解决scheme

 function isAsync (func) { const string = func.toString().trim(); return !!( // native string.match(/^async /) || // babel (this may change, but hey...) string.match(/return _ref[^\.]*\.apply/) // insert your other dirty transpiler check // there are other more complex situations that maybe require you to check the return line for a *promise* ); } 

这是一个非常有效的问题,我很不高兴有人投了他的票。 这种types检查的主要用例是一个库/框架/装饰器。

这些是早期的,我们不应该倒退VALID的问题。