Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created January 30, 2017 04:11
Show Gist options
  • Save akirattii/00da0fdfee8e400e35e70e9e2b9a9230 to your computer and use it in GitHub Desktop.
Save akirattii/00da0fdfee8e400e35e70e9e2b9a9230 to your computer and use it in GitHub Desktop.
Synchronous iteration for milding cpu overload using node-step with generator
const Step = require("step");
Step(
//
// ** 1st Step:
//
function() {
console.log("### 1st Step:");
let arr = ["aaa", "bbb", "ccc"];
let err, result;
// Iter:
let ite = function*(cb) {
for (let len = arr.length, i = 0; i < len; i++) {
console.log("ite: waiting for `next()`...");
yield toUpper(i);
};
err = null;// error is null if ok
result = arr; // sets upperCased strings as result
cb(err, result);
}(this); // to the next step
// first fire!
ite.next();
// Any fn to be executed in above generator:
function toUpper(idx) {
setTimeout(function() {
console.log(` toUpper: ${arr[idx]} => ${arr[idx].toUpperCase()}`);
arr[idx] = arr[idx].toUpperCase();
console.log(" toUpper: doing next()");
arr[idx] = arr[idx].toUpperCase();
return ite.next();
}, 1000);
}
},
//
// ** 2nd Step:
//
function(err, result) {
if(err) throw err;
console.log("### 2nd Step:");
console.log(`err:${err}, result:${result}`);
});
// Result:
//
// ### 1st Step:
// ite: waiting for `next()`...
// toUpper: aaa => AAA
// toUpper: doing next()
// ite: waiting for `next()`...
// toUpper: bbb => BBB
// toUpper: doing next()
// ite: waiting for `next()`...
// toUpper: ccc => CCC
// toUpper: doing next()
// ### 2nd Step:
// err:null, result:AAA,BBB,CCC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment