jwitos
jwitos

Reputation: 502

(Koa.js) Generators and yield basics

I'm trying to understand how generators work (generally and in koa). I have files:

Rooms.js - it handles placing user to room (socket.io) and stuff, when player is assigned to the room I want to run Game.js module

var Game = require('./Game');
(...)
Game.startGame(roomId)

Game.js - function startGame*() is called from Rooms.js: and it should do some code, then I want it to wait let's say 500ms, and after that it should run some more code.

exports.startGame = function *(roomid) {
  console.log("before sleep")
  yield Utility.sleep(500)
  console.log("after sleep")
}

and sleep() function in Utility.js:

exports.sleep = function(ms){
  return function(cb) {
    setTimeout(cb, ms);
  };
}

But it doesn't work - the generator function in Game.js. And I don't have any clue what is wrong there. Please help.

Upvotes: 0

Views: 360

Answers (1)

James Moore
James Moore

Reputation: 1901

Generators must be acted on by outside code, a 'runner' such as the co library.

Koajs uses the co library under the covers, so any middleware is run by co.

Its not clear to me if you are running Game.startGame(roomId) inside a runner (koajs middleware), and since it's a generator you must yield it (which your code is missing).

I have a screencast on Generators that you might find helpful

http://knowthen.com/episode-2-understanding-javascript-generators/

Here is an example of your code (compressed to one file) that is runnable:

// 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);
});

here is the output:

$node example.js
before sleep
after sleep

Upvotes: 2

Related Questions