title: Catching and returning an error from a callback that may be asynchronous
body: <p>I have a function like so:</p>
  <pre><code>const x = y(callback);
  x();
  </code></pre>
  <p>It may be called with a synchronous or asynchronous callback:</p>
  <pre><code>const a = y(() =&gt; 42);
  const b = y(async () =&gt; Promise.resolve(42));
  </code></pre>
  <p>The function <code>y</code> should take a callback, that can be synchronous or asynchronous. Is it possible to catch a thrown error from either a synchronous or asynchronous callback?</p>
  <p>I can't simply wrap the callback in a <code>try/catch</code>:</p>
  <pre><code>const y = (callback) =&gt; function () {
    try {
      return callback(...arguments);
    }
    catch (callbackError) {
      throw callbackError;
    }
  };
  </code></pre>
  <p>because that doesn't catch the errors thrown from promises. I can't just chain a <code>.catch</code> onto the callback as it might not be a promise.</p>
  <p>I've read that checking if a function is a promise before calling it <a href="https://stackoverflow.com/questions/38508420/how-to-know-if-a-function-is-async">may not trivial/may not be possible</a>.</p>
  <p>I can't call it to check if it returns a promise before chaining the <code>catch</code> onto it because if it throws, the <code>catch</code> would not have yet been chained onto the call</p>
  <p>Is there a way to catch an error from a callback that may or may not be a promise?</p>
  <hr />
  <p>Per the comments, I should have specified I don't want the function to return a promise. That is:</p>
  <pre><code>const a = y(() =&gt; { throw new Error(); })();
  console.log(a instanceof Error);
  
  const b = y(async () =&gt; { throw new Error(); })();
  console.log(b instanceof Error);
  
  const c = y(() =&gt; 42)();
  console.log(c === 42);
  
  const d = y(async () =&gt; Promise.resolve(42))();
  console.log(d instanceof Promise);
  </code></pre>
  <p>should all be true. Simply put, I want to return an error or the result</p>