chiffchaff
Cancellable promises with progress reporting. A more object-oriented approach to using bluebird.
Example
Note: Like chiffchaff itself, this example is written in ES2015. Please familiarize yourself with ES2015 before tackling it.
Let's say we want to create a DownloadTask
class that we can use to download
a file over HTTP. This would be a typical instantiation of that class:
const url = 'http://media.w3.org/2010/05/sintel/trailer.mp4'const videoDownloadTask = url
By default, a chiffchaff Task
will emit start
, progress
, and end
events
whenever its status changes. Thus, we can listen for those, for example to log
progress information to the console.
videoDownloadTask
A Task
will not carry out any work until its start
function is called. That
one returns a
cancellable promise
which will be fulfilled with the result of the task. Hence, we start our
download task as follows:
videoDownloadTaskstart
Let's say that after a second, we change our mind and want to cancel the
download. It's as simple as calling cancel
on the task.
Now that we've established the DownloadTask
API, let's actually implement the
class. As you may already have guessed, it's essentially a wrapper for Node's
http.get
.
To avoid having to enable bluebird's cancellation feature manually, chiffchaff
exports a preconfigured Promise
alongside its own Task
. You can also access
it as require('chiffchaff').Promise
if you prefer CommonJS.
{ super this_url = url this_request = null this_downloaded = 0 this_contentLength = 0 this_data = } // Subclasses of Task must only override the _start function. It returns a // cancellable promise for the work which the task is carrying out. { return { // Hold on to the callbacks so we can use them below. this_resolve = resolve this_reject = reject this_request = http // If the task gets cancelled, abort the underlying HTTP request. } } { if responsestatusCode !== 200 this else this_contentLength = // Whenever a task has updated information on its progress, it should call // _notify with two numbers: the completed amount and the total amount. // In this case, we're passing the number of bytes downloaded and the // total size of the file. this response } { this_downloaded += chunklength this_data this }
A more robust implementation of DownloadTask
will eventually be made available
as a Node module.
Maintainer
License
MIT