← Back To API Reference

Promise.coroutine

Promise.coroutine(GeneratorFunction(...arguments) generatorFunction, Object options) -> function

Returns a function that can use yield to yield promises. Control is returned back to the generator when the yielded promise settles. This can lead to less verbose code when doing lots of sequential async calls with minimal processing in between. Requires node.js 0.12+, io.js 1.0+ or Google Chrome 40+.

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

Running the example:

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

When called, the coroutine function will start an instance of the generator and returns a promise for its final value.

Doing Promise.coroutine is almost like using the C# async keyword to mark the function, with yield working as the await keyword. Promises are somewhat like Tasks.

Tip

You are able to yield non-promise values by adding your own yield handler using Promise.coroutine.addYieldHandler or calling Promise.coroutine() with a yield handler function as options.yieldHandler.