Use the await keyword with Q promises to tame your async code
Warning!! the api is not yet stable, it will be soon, so watch & star this repository if you're interested
QJS adds a
yield keyword for use with Q promises. To use it, you must 'compile' your code. Unfortunately this somewhat destroy's your stack traces at the moment. I'd really like to come up with a way of repairing them. Other than that though, it's pretty much perfect :)
require'qjs'compilemodule//All your module code must go in here.return yielda + yieldb;;;
var Q = require'q';var math = require'./PromisedMath';mathaddQdelay3 5000 Qdelay2 5000thenconsole.logend;
If you ran consumer.js, it would create a promise for
2 and a promise for
3. These promises both take 5 seconds to resolve (you could imagine them being pulled from a server). The add method recieves both promises and then waits (sequentially) for both to be resolved before adding them together. We then log the output of 5.
Because the time starts when we create the promise, it is not important that we then wait for them sequentially.
var Q = require'q';var api = require'api';moduleexportsgetNextMessage = QnbindapigetNextMessage;
require'qjs'compilemodule//All your module code must go in here.var api = require'./api';while message = yieldapigetNextMessageconsole.logmessage;;;
qjs library consists of a single function that compiles code that contains yield into code that can run asyncronously. If any part of a module requires use of yield like keywords, the whole module should be wrapped by the qjs compiler.
Inside the compiler you have access to
yield which will return the result of a promise, once it has been resolved. You also get access to
Q which is the promise library and simply saves you putting
var Q = require('q'); at the top of your file.
Please fork and update this project, it's very much a work in progress, but hopefully someone will find it useful.
I will accept pull requests that fix these, and I intend to fix all of them in the near future. In the mean time, if I find it and can't fix it I document it.
||are not always as lazy as they should be if there's an yield on the right hand side of the expression.