let gseries = require('../node_modules/gseries');
function asynce(index) {
return new Promise(function (res, rej) {
console.log('index(%s) start', index);
setTimeout(function () {
console.log('index(%s) end', index);
res(index);
}, 3000);
});
}
function* main() {
yield asynce(0);
yield asynce(1);
return asynce(2);
}
let p = gseries(main);
--------------------------------------------------------
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
module.exports = gseries;
function gseries(fn, data) {
return new Promise(function (res, rej) {
let it = fn();
job(data);
//----------------------------
function job(d) {
// 主要要不斷重複的步驟
let g = it.next(d);
let p = g.value;
// p.then(...)
if (g.done) {
res(p);
} else if (p instanceof Promise) {
p.then(function (d) {
job(d);
}, function (err) {
rej(err);
});
}else{
job(p);
}
}
});
}