I'm not sure where exactly you're stuck but pointing you in the general direction should suffice:
- You have an interface that works with a pipe and events
- You need to promisify that interface.
So what you need to do is:
- Find out what's the 'completion' event of the download.
- Create a promise and resolve it on that event, reject it on the failed event.
- Return that promise.
Promisifying can be done in several ways:
By the promise library. Bluebird contains a really clever promisifier using dynamic code generation that relies on the JIT - it is very fast - but it's built for the NodeJS "nodeback" case. (i.e. error passed as first argument of the callback.)
Using the
Deferred
object. Generally that way is more error prone.Using
Promise.method
in Bluebird, which is great for promisifying APIs easily but is not really our case here.Using the
Promise
constructor. This is what we'll do here. It's also standards complaint.
Generally, the interface of the promise constructor is:
new Promise(function(resolve,reject){
resolve(); // this resolves the promise
reject(); // this rejets the promise
});
Note, promisifying event emitters only works well when they fire on a finish event and do so once. Promises are one time, once they settle they can't change state. Events can fire multiple times. It's perfectly fine to promisify things like "load"
events or "finished"
events - but don't promisify things that repeat multiple times.
Your second map should be something like:
map(function (downloadItem) {
console.log('downloading files');
downloadItem.result.once('close', function () {
console.log('closed');
});
var pipeAction = downloadItem.result.pipe(fs.createWriteStream(process.cwd() + "/zips/" + downloadItem.input.destination));
return new Promise(function(resolve,reject){
pipeAction.on("end",function(){ //waits for data to be consumed
// pipe has ended here, so we resolve the promise
resolve();
});
});
}).
You should generally extract promisifications into dedicated methods. For example, the above could be a promisifyPipe
or similar.