Skip to content

Instantly share code, notes, and snippets.

@dickeylth
Last active August 29, 2015 14:18
Show Gist options
  • Save dickeylth/b6a17b32003e43505b3a to your computer and use it in GitHub Desktop.
Save dickeylth/b6a17b32003e43505b3a to your computer and use it in GitHub Desktop.
es6-co-demo
var co = require('co');

function printTime() {
	"use strict";
	return '[' + Date.now() + '] ';
}

co(function* () {
	"use strict";

	var a = new Promise(function (resolve, reject) {
		setTimeout(function () {
			console.log(printTime() + 'a done. ');
			resolve('abc');
		}, 3000);
	});

	var b = new Promise(function (resolve, reject) {
		setTimeout(function () {
			console.log(printTime() + 'b done.  ');
			resolve('def');
		}, 1000);
	});

	var c = new Promise(function (resolve, reject) {
		setTimeout(function () {
			console.log(printTime() + 'c done.  ');
			resolve('pkq');
		}, 2000);
	});

	console.log(printTime() + 'start...');

	var aValue = yield a;
	console.log(printTime() + 'a yielded' + ' - ' + aValue);

	var bValue = yield b;
	console.log(printTime() + 'b yielded' + ' - ' + bValue);

	var cValue = yield c;
	console.log(printTime() + 'c yielded' + ' - ' + cValue);
})
	.then(function () {
		"use strict";
		console.log(printTime() + 'co end');
	})
	.catch(function (e) {
		"use strict";
		console.error(e);
	});
/usr/local/bin/node --debug-brk=54935 --nolazy --harmony co-test.js
Debugger listening on port 54935
[1428660321055] start...
[1428660326148] a done. 
[1428660329191] a yielded - abc
[1428660331255] b done.  
[1428660334298] b yielded - def
[1428660336360] c done.  
[1428660339401] c yielded - pkq
[1428660340413] co end
@popomore
Copy link

var co = require('co');

function printTime() {
    "use strict";
    return '[' + Date.now() + '] ';
}

co(function* () {
    "use strict";

    console.log(printTime() + 'start...');

    var aValue = yield new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(printTime() + 'a done. ');
            resolve('abc');
        }, 3000);
    });
    console.log(printTime() + 'a yielded' + ' - ' + aValue);

    var bValue = yield new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(printTime() + 'b done.  ');
            resolve('def');
        }, 1000);
    });
    console.log(printTime() + 'b yielded' + ' - ' + bValue);

    var cValue = yield new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(printTime() + 'c done.  ');
            resolve('pkq');
        }, 2000);
    });
    console.log(printTime() + 'c yielded' + ' - ' + cValue);
})
    .then(function () {
        "use strict";
        console.log(printTime() + 'co end');
    })
    .catch(function (e) {
        "use strict";
        console.error(e);
    });

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