Skip to content

Instantly share code, notes, and snippets.

@divs1210
Last active December 1, 2017 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divs1210/7aaf47c75cbca86fdfcd2366267637fe to your computer and use it in GitHub Desktop.
Save divs1210/7aaf47c75cbca86fdfcd2366267637fe to your computer and use it in GitHub Desktop.
coroutines.js walkthrough

Setup

Channels & go

var c = chan();

go(function() {
  // async block
});

go(function() {
  // async block
  // parks if c empty!
  return take(c, function(v) {
    // called when v arrives on c
  });
});

go(function() {
  // async block
  // parks if c full!
  return put(c, 'hi!', function() {
    // optional
    // called when put successful
  });
});

What can't we port from core.async?

var c = chan();
var d = chan();

// Real life
go(() => {
  console.log('hi!');
  
  return take(c, (x) => {
    console.log(x);
    goput(d, x+1);

    gotake(d, (y) => {
      console.log(y);
    });
  });
});

// If JS had macros
go(() => {
  console.log('hi');

  var x = take(c);
  console.log(x);
  put(d, x+1);
  
  var y = take(d);
  console.log(y);
});

Actors

// DB
const userHitCounts = {};

// Message Queue
const messageQ = chan(100);

// Kaioken Consumer
goconsume(messageQ, (msg, recur) => {  
  var currScore = userHitCounts[msg.id] || 0;
  userHitCounts[msg.id] = currScore + msg.count;
  
  recur();
});

// send an asynchronous message
goput(messageQ, {id: 42, count: 1});

for(i=0; i<1000; i++)
  goput(messageQ, {id: 40, count: 1});
@divs1210
Copy link
Author

divs1210 commented Nov 26, 2017

Can run thousands of async consumers at a time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment