node – Coffee and Code https://blog.coffeeandcode.com Thoughts on web development, collaboration, our local tech community, and probably tacos. Thu, 26 Oct 2017 18:04:43 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.3 You Promised Me! https://blog.coffeeandcode.com/you-promised-me/ Sat, 23 Apr 2016 12:18:37 +0000 https://blog.coffeeandcode.com/?p=86 Continue reading "You Promised Me!"

]]>
I absolutely love Promises in JavaScript code. As a person who started their programming career in DHTML I’ve seen a ton of new features added over time, but none have seemed as powerful as being able to control the flow of my software.

I want to focus on one aspect of Promises for this post though, exceptions. If a Promise function has an exception thrown, the promise will be rejected with the exception as the value.

Here’s an example:

new Promise(function(resolve, reject) {
  throw new Error('ARGHHH!');
}).catch(function(error) {
  console.log('The error is:', error);
});

What I don’t have to do is to do any try / catch to make sure the exception does not halt my program. Great!

One thing that sometimes slips my memory though is that the implicit catching of errors is only done on the function being executed inside the Promise (the executor), it does not extend to other callbacks that are called by that method.

const fs = require('fs');

new Promise(function(resolve, reject) {
  // Error thrown if the file "post.md" does not exist
  fs.readFile('post.md', function(err, data) {
    if (err) throw err;
  });
}).catch(function(error) {
  console.log('We will never get here.');
});

If the file post.md does not exist, Node will throw an along the lines of: Error: ENOENT: no such file or directory, open 'post.md'. That error will not be caught and your app will have a bad day.

The reason is that the callback executed in the readFile method creates a new context for execution and you have to rely on normal try / catch logic if your intent is for the Promise’s final catch statement to have your error.

const fs = require('fs');

new Promise(function(resolve, reject) {
  fs.readFile('post.md', function(err, data) {
    try {
      // It's now ok to throw an error here.
      // You can also just reject it.
      if (err) throw err;
    } catch (error) {
      // Reject any caught errors.
      reject(error);
    }
  });
}).catch(function(error) {
  console.log('The error is:', error);
});

Hopefully this helps you make sure your code’s flow control is exactly as you intended.


Sign up for our newsletter to learn some more tips and tricks, or just keep up to date on what we’re doing.

If you’d like to teach those tips and tricks to your team, we offer coaching and training opportunities for existing team members at your company.

]]>