medikoo / deferred

Modular and fast Promises implementation for JavaScript
ISC License
364 stars 20 forks source link

Q's makeNodeResolver() analogue #17

Closed zowers closed 11 years ago

zowers commented 11 years ago

need something like Q's makeNodeResolver() - to pass a deferred to a Node callback https://github.com/kriskowal/q/blob/master/q.js#L608

medikoo commented 11 years ago

Is it about node function that takes async function as one of its arguments? Can you clarify with example, or link the documentation of such?

zowers commented 11 years ago

as per Q's doc https://github.com/kriskowal/q#adapting-node

Finally, if you're working with raw deferred objects, there is a makeNodeResolver method on deferreds that can be handy:

var deferred = Q.defer();
FS.readFile("foo.txt", "utf-8", deferred.makeNodeResolver());
return deferred.promise;
medikoo commented 11 years ago

In deferred there's promisify for that. Out of given async function it creates one that returns promise:

return deferred.promisify(FS.readFile)("foo.txt", "utf-8");

It's nicer approach, as once you create a wrapper, you may reuse it as many times you like. Thanks to that you can construct very readable flows:

var readFile = deferred.promisify(FS.readFile);

// Return content of two files joined
return deferred(readFile('foo.txt', 'utf-8'), readFile('bar.txt', 'utf-8')).invoke('join', '');

I'm closing it for now, but if for some reason it's still not solution you're looking for let me know.