Maybe I'm missing something, but I find C#'s async/await much more intuitive (not having written any C# and currently working on a pet project using promises with Node and Q).
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:
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?
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.
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.
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?