Skip to content

Instantly share code, notes, and snippets.

@futurist
Forked from oklai/co.js
Created January 6, 2016 06:54
Show Gist options
  • Save futurist/0176b0a0c2f65ca6a4bf to your computer and use it in GitHub Desktop.
Save futurist/0176b0a0c2f65ca6a4bf to your computer and use it in GitHub Desktop.
co.js simple
'use strict';
/**
* co.js simple
*/
// api
//
// var co = require('co');
//
// function getJSON (url) {
// return new Promise(function (resolve, reject) {
// setTimeout(function () {
// resolve({id: 1});
// }, 1000);
// });
// }
// function getUser (id) {
// return new Promise(function (resolve, reject) {
// setTimeout(function () {
// resolve({name: 'username', ege: 28});
// }, 1000);
// });
// }
//
// co(function* test () {
// var data = yield getJSON('http://domain.com/user.json');
// var user = yield getUser(data.id);
// console.log(user);
// });
function Co (task) {
var self = this;
// run generator function as first
if (typeof task === 'function') {
task = task();
}
// run iterator next
function run (task, resVal) {
let taskRet = task.next(resVal);
let retVal = taskRet.value;
if (!taskRet.done) {
var p;
if (Array.isArray(retVal)) {
// for promise array
p = Promise.all(retVal).then(function(resVals) {
run(task, resVals);
});
} else {
// for promise item
p = taskRet.value.then(function (resVal) {
run(task, resVal);
});
}
// Catch the exception
p.catch(function(reason){
self.catchCallback(reason);
});
}
}
run(task);
// catch
self.catch = function (callback) {
self.catchCallback = callback || function () {};
};
}
module.exports = function (task) {
console.log('runing co');
return new Co(task);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment