Created
December 31, 2014 03:40
-
-
Save oklai/154ba68fff5b413eff9e to your computer and use it in GitHub Desktop.
co.js simple
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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