1

I write a function to handle exceptions thrown from async functions like:

protected safeAsync(f : e.RequestHandler) : e.RequestHandler {
    /* how to detect if `f` is an async function here ?? */
    const binded = f.bind(this);
    return async function innerCall(req : e.Request, res : e.Response, next : Function) {
        try {
            return await binded(req, res, next);
        } catch (err) {
            log.debug(err);
            return next(err);
        }
    }
}

The parameter f is supposed be an async function, such as

public async signupPost(req : e.Request, res : e.Response, next : Function) {/*...*/}

My question is:

In safeAsync, is there a way to detect if f is an async function, so I can log unexpected call to safeAsync ?

1
  • I believe it shouldn't matter if f has an async keyword or not. You should still be able to await it as long as it returns a promise. Commented Jan 30, 2016 at 16:02

2 Answers 2

5

Since this is a runtime check the question you should be asking is whether or not JavaScript provides a way to check if a function is async. The answer is no, there is no fool proof way to tell if a function is async or not, it could even be both.

Sign up to request clarification or add additional context in comments.

Comments

0

You can force it to be async just be doing Promise.resolve(f()), function "f" may return a promise or not but resolve will make it a promise anyway.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.