Skip to content

Instantly share code, notes, and snippets.

@benjie
Last active November 17, 2017 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjie/e6238973b1c29d01cb117bf9b1bcebf7 to your computer and use it in GitHub Desktop.
Save benjie/e6238973b1c29d01cb117bf9b1bcebf7 to your computer and use it in GitHub Desktop.
Ensure promises are awaited (or have `.catch(...)` installed) within same tick

In node v8 the code in test.js will result in the following:

(node:47866) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Thrown error
(node:47866) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Error: Thrown error
    at foo (/Users/benjiegillam/Documents/test/test.js:2:9)
    at Object.<anonymous> (/Users/benjiegillam/Documents/test/test.js:5:17)
    at Module._compile (module.js:612:30)
    at Object.Module._extensions..js (module.js:623:10)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)
    at Function.Module._load (module.js:486:3)
    at Function.Module.runMain (module.js:653:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
(node:47866) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)

Note the "Unhandled promis rejection" warnings because there was no rejection handler installed on the promise result within the same tick - it wasn't until the next tick that the handler was installed (which then results in the "rejection was handled asynchronously" warning.

In future node versions this will cause Node to exit before the error is even handled.

async function foo() {
throw new Error("Thrown error");
}
const promise = foo();
setImmediate(async function bar() {
try {
await promise;
} catch (e) {
console.error(e);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment