JavaScript中如何判断一个函数是同步函数,异步函数或者生成器函数?
function a() {}
function* b() {}
async function c() {}
const d = () => {};
const e = async () => {};
function f(){
return new Promise((resolve)=>{resolve(1)}
}
console.log(`a`, a,a.prototype);
console.log(`b`, b,b.prototype);
console.log(`c`, c,c.prototype);
console.log(`d`, d,d.prototype);
console.log(`e`, e,e.prototype);
console.log 可以显示是什么函数,但怎么通过代码识别?
回复
1个回答

test
2024-06-29
function getTypeOfFunction(fn) {
if (fn.constructor.name === 'AsyncFunction') {
return 'Async Function';
} else if (fn.constructor.name === 'GeneratorFunction') {
return 'Generator Function';
} else if (fn.constructor.name === 'Function' || fn.constructor.name === 'ArrowFunction') {
return 'Sync Function';
} else {
return 'Not a function';
}
}
function a() {}
function* b() {}
async function c() {}
const d = () => {};
const e = async () => {};
console.log(`a is a ${getTypeOfFunction(a)}`);
console.log(`b is a ${getTypeOfFunction(b)}`);
console.log(`c is a ${getTypeOfFunction(c)}`);
console.log(`d is a ${getTypeOfFunction(d)}`);
console.log(`e is a ${getTypeOfFunction(e)}`);
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容