by martingordon · 13y ago · 0 comments
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:
results = getResults(); writeTable1(results.foo); writeTable2(results.bar); writeTable3(results.baz);
Using Node and Q: db.load().then(()-> setupDB(db)).then(()-> collectData(db)).done()
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?
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'
});Perhaps I should look into IcedCoffeeScript (http://maxtaco.github.io/coffee-script/) instead of plain CS.