Hi! I have been using Nodejs to write asynchronous server. I mix the event loop and generator to construct my program. Just like:
function* sayHelloWorld(ynext) {
var hello = "", world = "";
yield setTimeout(function () {
hello = "Hello";
ynext();
}, 1000);
yield setTimeout(function () {
world = "world";
ynext();
}, 1000);
return [hello + " " + world + "!"];
}
var server = new Http.Server();
var app = new Application();
server.on("request", app.exec);
app.on("/helloworld", function* (ynext, next, req, res) {
var [HelloWorld] = yield* sayHelloWorld(ynext);
console.log(HelloWorld);
});
I noticed the built-in asyncdispatch module, very much like the promise of JavaScript. And I added a timeout check, and did some tests.
Here are some of my suggestions, this is the code that I feel:
proc server() =
var
server = newAsyncHttpServer()
mysql = newAsyncMysql()
logger = newAsyncLogger()
while true:
(req, res) = server.serve()
echo req.body # parse(req.body)
async(req, res):
# These two sql are serial, their order is very important.
(error1, replies1) = await mysql.query("select * from users")
echo error1, replies1
(error2, replies2) = await mysql.query("select * from blogs")
echo error2, replies2
# These two sql are not serial, we don't care about their order.
fut3 = mysql.query("insert into logs set newlog = 'log'")
fut3.callback =
proc (error3, replies3) =
echo error3, replies3
fut4 = mysql.query("insert into docs set newdoc = 'doc'")
fut4.callback =
proc (error4, replies4) =
echo error4, replies4
# Response.
await res.send(replies2)
async(req, res):
await logger.write("request in")
echo "Request in"
server()
Yeah. A bit like goroutine of go-lang, or parallel of threadpool module. (Perhaps using a macro to solve this problem ?)
async(args): # A
await oneAsync
await twoAsync
asyncCheck threeAsync # not await
asyncCheck fourAsync # not await
async(args): # B
await oneAsync
await twoAsync
async(args): # C
await oneAsync
await twoAsync
In this example, oneAsync in A, B, C together execute. A.twoAsync will wait A.oneAsync, B.twoAsync will wait B.oneAsync, and C.twoAsync will wait C.oneAsync. A B C independently manage their execution order.
And I found asynchttpserver.serve provides a callback function. I hope the proc can return a Future, or can get req, res from the return result.
After this program is compiled, perhaps similar to:
var args = server.serve()
proc A(args) {.async.} = # A
await oneAsync
await twoAsync
asyncCheck threeAsync # not await
asyncCheck fourAsync # not await
asyncCheck A(args)
proc B(args) {.async.} = # B
await oneAsync
await twoAsync
asyncCheck B(args)
proc C(args) {.async.} = # C
await oneAsync
await twoAsync
asyncCheck C(args)