How do I handle exceptions globally with native promises in node.js?

Edit We’ve finally fixed this in Node.js 15, it took 5 years but native promise rejections now behave like uncaught exceptions – so it’s fine to just add a process.on(‘uncaughtException’ handler. In Modern Node.js Starting with io.js 1.4 and Node 4.0.0 you can use the process “unhandledRejection” event: process.on(“unhandledRejection”, function(reason, p){ console.log(“Unhandled”, reason, p); // … Read more

ES6 promise execution order for returned values

Promise.resolve is specified to return a resolved promise (mind-blowing, right? 25.4.4.5, 25.4.1.5, 25.4.1.3.). a.then() therefore enqueues a job immediately (25.4.5.3.1, step 8) each time. .then() never returns a fulfilled promise according to this spec (for something interesting, try Promise.resolve().then() in your Chrome console¹). Let’s name the promise a.then(v => Promise.resolve(“A”)) and some of its associated … Read more

What is the intention behind clause 2.2.4 of Promise/A+ spec?

The reasoning is that when the callbacks are always asynchronous instead of possibly asynchronous, it gives more consistent and reliable api to use. Consider the following code var pizza; browseStackOverflow().then(function(){ eatPizza(pizza); }); pizza = yesterdaysLeftovers; Now that snippet clearly assumes the onFulfilled will not be called right away and if that wasn’t the case we … Read more

fs.writeFile in a promise, asynchronous-synchronous stuff

As of 2019… …the correct answer is to use async/await with the native fs promises module included in node. Upgrade to Node.js 10 or 11 (already supported by major cloud providers) and do this: const fs = require(‘fs’).promises; // This must run inside a function marked `async`: const file = await fs.readFile(‘filename.txt’, ‘utf8’); await fs.writeFile(‘filename.txt’, … Read more

What are asynchronous functions in JavaScript? What is “async” and “await” in JavaScript?

Intro JavaScript has an asynchronous model. Whenever an asynchronous action is completed you often want to execute some code afterwards. First callbacks were often used to solve this problem. However, when programming code with multiple asynchronous elements a problem arises using callbacks. Because when you nest multiple callbacks inside each other the code becomes hard … Read more