(Koa.js) 生成器和产量基础知识
(Koa.js) Generators and yield basics
我正在尝试了解生成器的工作原理(通常和在 koa 中)。我有文件:
Rooms.js - 它处理将用户放置到房间 (socket.io) 和其他东西,当玩家被分配到我想要的房间时 运行 Game.js
模块
var Game = require('./Game');
(...)
Game.startGame(roomId)
Game.js - 函数 startGame*()
是从 Rooms.js 调用的:它应该执行一些代码,然后我希望它等待让我们比如说 500 毫秒,然后它应该 运行 一些更多的代码。
exports.startGame = function *(roomid) {
console.log("before sleep")
yield Utility.sleep(500)
console.log("after sleep")
}
和 Utility.js 中的 sleep() 函数:
exports.sleep = function(ms){
return function(cb) {
setTimeout(cb, ms);
};
}
但它不起作用 - Game.js 中的生成器函数。而且我不知道那里出了什么问题。请帮忙。
生成器必须由外部代码操作,'runner' 例如 co 库。
Koajs 在幕后使用 co 库,因此任何中间件都是 运行 by co.
我不清楚你是否在 运行ner(koajs 中间件)中 运行ning Game.startGame(roomId),因为它是一个生成器,你必须 yield 它(你的代码丢失了)。
我有一个关于生成器的截屏视频,你可能会觉得有用
http://knowthen.com/episode-2-understanding-javascript-generators/
这是您的代码示例(压缩到一个文件)运行可用:
// example.js
'use strict';
let co = require('co');
let startGame = function *(roomid) {
console.log("before sleep")
yield sleep(500)
console.log("after sleep")
}
let sleep = function (ms){
return function(cb){
setTimeout(cb, ms);
}
}
co(function *(){
// your code was missing yield
yield startGame(123);
}).catch(function(err){
console.log(err);
});
这是输出:
$node example.js
before sleep
after sleep
我正在尝试了解生成器的工作原理(通常和在 koa 中)。我有文件:
Rooms.js - 它处理将用户放置到房间 (socket.io) 和其他东西,当玩家被分配到我想要的房间时 运行 Game.js
模块
var Game = require('./Game');
(...)
Game.startGame(roomId)
Game.js - 函数 startGame*()
是从 Rooms.js 调用的:它应该执行一些代码,然后我希望它等待让我们比如说 500 毫秒,然后它应该 运行 一些更多的代码。
exports.startGame = function *(roomid) {
console.log("before sleep")
yield Utility.sleep(500)
console.log("after sleep")
}
和 Utility.js 中的 sleep() 函数:
exports.sleep = function(ms){
return function(cb) {
setTimeout(cb, ms);
};
}
但它不起作用 - Game.js 中的生成器函数。而且我不知道那里出了什么问题。请帮忙。
生成器必须由外部代码操作,'runner' 例如 co 库。
Koajs 在幕后使用 co 库,因此任何中间件都是 运行 by co.
我不清楚你是否在 运行ner(koajs 中间件)中 运行ning Game.startGame(roomId),因为它是一个生成器,你必须 yield 它(你的代码丢失了)。
我有一个关于生成器的截屏视频,你可能会觉得有用
http://knowthen.com/episode-2-understanding-javascript-generators/
这是您的代码示例(压缩到一个文件)运行可用:
// example.js
'use strict';
let co = require('co');
let startGame = function *(roomid) {
console.log("before sleep")
yield sleep(500)
console.log("after sleep")
}
let sleep = function (ms){
return function(cb){
setTimeout(cb, ms);
}
}
co(function *(){
// your code was missing yield
yield startGame(123);
}).catch(function(err){
console.log(err);
});
这是输出:
$node example.js
before sleep
after sleep