Posts

Showing posts from April, 2016

Trees of Promises in ES6

This blog post shows how to handle trees of ES6 Promises , via an example where the contents of a directory are listed asynchronously. The challenge We’d like to implement a Promise-based asynchronous function listFile(dir) whose result is an Array with the paths of the files in the directory dir . As an example, consider the following invocation: listFiles('/tmp/dir') .then(files => { console.log(files.join('\n')); }); One possible output is: /tmp/dir/bar.txt /tmp/dir/foo.txt /tmp/dir/subdir/baz.txt The solution For our solution, we create Promise-based versions of the two Node.js functions fs.readdir() and fs.stat() : readdirAsync(dirpath) : Promise<Array<string>> statAsync(filepath) : Promise<Stats> We do so via the library function denodify : import denodeify from 'denodeify'; import {readdir,stat} from 'fs'; const readdirAsync = denodeify(readdir); const statAsync = d

Tracking unhandled rejected Promises

In Promise-based asynchronous code, rejections are used for error handling. One risk is that rejections may get lost, leading to silent failures. For example: function main() { asyncFunc() .then(···) .then(() => console.log('Done!')); } If asyncFunc() rejects the Promise it returns then that rejection will never be handled anywhere. Let’s look at how you can track unhandled rejections in browsers and in Node.js. Unhandled rejections in browsers Some browsers (only Chrome at the moment) report unhandled rejections. unhandledrejection Before a rejection is reported, an event is dispatched that you can listen to: window.addEventListener('unhandledrejection', event => ···); The event is an instance of PromiseRejectionEvent whose two most important properties are: promise : the Promise that was rejected reason : the value with which the Promise was rejected The following example demonstrates how this event works: window.addEven