Re:Promises/A+
by ShellfishMeme on Tuesday July 09, 2013 @08:21AM
(#6012255)
If you make your `db.load` method resolve the promise with `this` (where `this` is `db`), and do the same for `setupDB` and `collectData` you can easily chain them without having to have a reference to `db`.
db.load()
.then(setupDB)
.then(collectData);
That way it looks much more like your blocking code.You are currently basically throwing away the value you `resolve` with, where you should instead resolve with what would be the return value if it was a sync function so you can `.then` the function that takes the return value and returns a promise to be resolved with its return value.
// Sync
var foo = function () { return 'foo' };
var addBar = function (foo) { return foo + 'bar'; }
addBar(foo()) == 'foobar'
// Promise using Q
var foo = function () { return Q.resolve('foo') };
var addBar = function (foo) { return Q.resolve(foo + 'bar'); }
foo.then(addBar).done(function (result) {
result == 'foobar'
});It's worth noting that C#'s async/await is based directly on promises; they are called `Task<T>` in .NET. Indeed, they share a common ancestor I believe; .NET 4.5's `Task<T>` is derived from F#'s `Async<T>`, and both `Async<T>` and JavaScript promises are based on E's promises.
Re:Promises/A+
by martingordon on Wednesday July 10, 2013 @10:16AM
(#6019734)
Yeah, I think the big difference for me is the language support. You can just await a method call instead of having to wrap the remainder of your block in a function.
Perhaps I should look into IcedCoffeeScript (http://maxtaco.github.io/coffee-script/) instead of plain CS.
My issue with promises is that I find myself working around the API/language when I actually want synchronous code. My app calls a JSON API and then writes the results to three tables (in sequence). In "normal", blocking code:
Using Node and Q: In which setupDB() returns a chain of three promises and collectData, which loops through the results and attach a new promise to the chain in order to return a chain of `n` promises.Are these just growing pains of learning a new paradigm or am I using the wrong tool for the job?
Can someone point me to any projects that actually use promises?