我试图让http://socket.io/与co合作 。
我试图在我的代码中异步执行一些任务。
io.on('connection', function (socket) { // <--- need to do something heavy here socket.on('something', function (data) { // <--- need to do something heavy here }); // <--- need to do something heavy here });这就是socket.io的工作原理。 我现在想加入co 。 我尝试过以下方法:
io.on('connection', function (socket) { co(function* () { yield something(); // <--- this works socket.on('something', function (data) { yield something(); // <--- this does not work }); yield something(); // <--- this works }); });获取此错误: SyntaxError: Unexpected strict mode reserved word
还有这个:
io.on('connection', function (socket) { co(function* () { yield something(); // <--- this works socket.on('something', function (data) { co(function* () { yield something(); // <--- this works }); }); yield something(); // <--- this works }); });我的问题是,这是应该如何使用,或者是我错过的东西。 包装一切似乎是一个非常多的额外代码?
I am trying to get http://socket.io/ working with co.
I am trying to do some tasks asynchronously in my code.
io.on('connection', function (socket) { // <--- need to do something heavy here socket.on('something', function (data) { // <--- need to do something heavy here }); // <--- need to do something heavy here });That's how socket.io works. I would like to add co to the mix now. I've tried the following:
io.on('connection', function (socket) { co(function* () { yield something(); // <--- this works socket.on('something', function (data) { yield something(); // <--- this does not work }); yield something(); // <--- this works }); });Get this error: SyntaxError: Unexpected strict mode reserved word
And this:
io.on('connection', function (socket) { co(function* () { yield something(); // <--- this works socket.on('something', function (data) { co(function* () { yield something(); // <--- this works }); }); yield something(); // <--- this works }); });My question is, is this how it is supposed to be used, or is ther something I've missed. It seems like an awful lot of extra code to wrap everything?
最满意答案
所以我又想了想。
io.on('connection', co.wrap(function *(socket) { yield something(); socket.on('something', co.wrap(function *(data) { yield something(); })); yield something(); }));这应该做的伎俩。 Wrap返回一个函数,然后返回一个Promise。 在这里,我们不关心后者。 有关Co.wrap的Co文档
So I thought about it again.
io.on('connection', co.wrap(function *(socket) { yield something(); socket.on('something', co.wrap(function *(data) { yield something(); })); yield something(); }));This should do the Trick. Wrap returns a function, which will return a Promise then. Here we don't care about the latter. Co Documentation On Co.wrap
更多推荐
发布评论