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 可以显示是什么函数,但怎么通过代码识别?

阅读 2.7k
2 个回答
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)}`);

我以前是利用函数的 .toString() 方法,检查 async 是否存在:/^async/.test(func.toString())

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题