Hacker News new | past | comments | ask | show | jobs | submit login

Can anyone explain why this pattern doesn't work? Or point me to some resource?

  function myApiFunc(callback)
  {
    /*
     * This pattern does NOT work!
     */
    try {
      doSomeAsynchronousOperation(function (err) {
        if (err)
          throw (err);
        /* continue as normal */
      });
    } catch (ex) {
      callback(ex);
    }
  }



Try/catch is not async and exceptions do not bubble up through the async context, which makes sense as the caller moved on with execution. Try this in your console:

    try {
        console.log("see, ");
        setTimeout(() => {throw new Error("oops")}, 100);
        console.log(
            "I can't assume here that"
            + " the prev. line succeeded"
        );
    } catch(e) {
        console.log("error!");
    }



much obliged




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: