4 ms·
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 wi
by martingordon 13y ago
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:
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?
- ShellfishMeme 13y agoIf 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' });
- domenicd 13y agoIt'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.
- martingordon 13y agoYeah, 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/ http://maxtaco.github.io/coffee-script/) instead of plain CS.