Promises & Generators

Promise.coroutine Returns a function that can use yield to yield promises. Control is returned back to the generator when the yielded promise settles. As close as javascript can get to async & await.

var Promise = require("bluebird");

function PingPong() { }

PingPong.prototype.ping = Promise.coroutine(function* (val) {
    console.log("Ping?", val);
    yield Promise.delay(500);
    this.pong(val+1);
});

PingPong.prototype.pong = Promise.coroutine(function* (val) {
    console.log("Pong!", val);
    yield Promise.delay(500);
    this.ping(val+1);
});

var a = new PingPong();

a.ping(0);

// $ node test.js
// Ping? 0
// Pong! 1
// Ping? 2
// Pong! 3
// Ping? 4
// Pong! 5
// Ping? 6
// Pong! 7
// Ping? 8
// ...

results matching ""

    No results matching ""