admin管理员组文章数量:1307836
I'm wondering if there's a way to determine if a function was defined using async function
or async (...) => ...
syntax?
I'm looking to implement the function isDefinedWithAsync
where:
isDefinedWithAsync(async function() { return null; }) === true;
isDefinedWithAsync(function() { return null; }) === false;
isDefinedWithAsync(async () => null) === true;
isDefinedWithAsync(() => null) === false;
Is it possible to implement isDefinedWithAsync
? And if so, how? Thanks!
I'm wondering if there's a way to determine if a function was defined using async function
or async (...) => ...
syntax?
I'm looking to implement the function isDefinedWithAsync
where:
isDefinedWithAsync(async function() { return null; }) === true;
isDefinedWithAsync(function() { return null; }) === false;
isDefinedWithAsync(async () => null) === true;
isDefinedWithAsync(() => null) === false;
Is it possible to implement isDefinedWithAsync
? And if so, how? Thanks!
2 Answers
Reset to default 8Yes,
Straight from the TC39 async/await Issues:
function isAsync(fn) {
return fn.constructor.name === 'AsyncFunction';
}
Here's a snippet that checks your 2 async
samples above and a 3rd non-async function:
function isAsync(fn) {
return fn.constructor.name === 'AsyncFunction';
}
// async functions
const foo = async () => { }
async function bar () { }
// non-async function
function baz () { }
console.log(isAsync(foo)) // logs true
console.log(isAsync(bar)) // logs true
console.log(isAsync(baz)) // logs false
But as mentioned in the rest of the ments on that issue, you shouldn't differentiate, at least conceptually, between async function
s and Promise
s since they behave the same.
Both can be await
-ed/then
-ed in the exact same way. An async
marked function always implicitly returns a Promise
.
Just an addition to Nicholas' great answer:
If you want to avoid using string parisons for type checks (due to the possibility of namespace collisions), you may be wanting to acplish the same thing with instanceof:
function isAsync(fn) {
return fn instanceof AsyncFunction;
}
In some environments you may get a ReferenceError
that "AsyncFunction is not defined".
This error can be resolved as follows:
const AsyncFunction = (async () => {}).constructor;
function isAsync(fn) {
return fn instanceof AsyncFunction;
}
Now even a silly case like the following:
isAsync({ constructor: { name: 'AsyncFunction' } });
will correctly return false
.
本文标签: javascriptDetermine if function was defined with quotasyncquotStack Overflow
版权声明:本文标题:javascript - Determine if function was defined with "async" - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741839982a2400442.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论