Tomáš Zato
Tomáš Zato

Reputation: 53193

Run two async.series in parallel

I am making a simple javascript game. Although I use alerts, because they're simple, I'm making the program as asynchronous as possible to make it easy to replace alerts with HTML. Currently, I set up new player and his two control keys like this:

var name = "Player";
// TODO: Replace with HTML element
name = prompt("Name?", "Player "+gameSlave.lines.length+1);
var color = 0xFFFFFF;
color = parseInt(prompt("Color (hex)?", "0x"+Math.round(Math.random()*16777215)).toString(16),16);
var keys = {right:null, left: null};

async.series([
    /** KEY GATHERING BOCK **/
      //Empty function to clear event loop buffer where keystrokes are still remaining
      function(callback){setTimeout(callback, 50);},
      function(callback){gatherControlKey("LEFT", function(key) {keys.left=key;callback()});},
      function(callback){gatherControlKey("RIGHT", function(key) {keys.right=key;callback()});},
    /** REMOTE PLAYER GATHERING BLOCK **/
      function(callback) {
        // If player is added, continue
        gameSlave.once("player.added", callback);
        // Ask game to create new player
        gameSlave.emit("player.requested", name, color);
      },
      function(callback) {
          alert("Player set!");
      },
]);

There are two independent blocks though:

  1. Gathering player control keys
  2. Asking server to create a player (server returns name, id and color).

So I'd like to run two sync chains asynchronously. Something like:

async.parallel([  //This throws error f you fill something in series
    async.series([ ... ]),
    async.series([ ... ])
]);

Upvotes: 1

Views: 1153

Answers (1)

Daniele Sassoli
Daniele Sassoli

Reputation: 898

I don't think your question was clear, you're not saying what's your specific problem you only say that it throws an exception, so I tried to guess what was wrong in your code. I think your syntax is incorrect, you should wrap the series in two functions, so they can have a callback to call when the series is finished. Shouldn't it be something like

async.parallel([
    function(pCb) {
        async.series([
            function(cb) {
                console.log(1);
                cb();
            }
        ], function() {
            console.log("completed first series");
            pCb();
        })
    },

    function(pCb) {
        async.series([
            function(cb) {
                console.log(2);
                cb();
            }
        ], function() {
            console.log("completed second series")
            pCb();
        })
    }
], function() {
    console.log("completed parallel");
});

If is dosn't solve the problem, then could you please make your question a bit more specific?

Upvotes: 3

Related Questions