Skip to content

simple implementation for chain #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions JavaScript/5c-chain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const wrapAsync =
(fn) =>
(...args) =>
setTimeout(() => fn(...args), Math.random() * 1000);

const readConfig = wrapAsync((data, callback) => {
console.log("data - ", data);
console.log("read config");

callback(null, data);
});

const selectFromDb = wrapAsync((query, callback) => {
console.log("query - ", query);
console.log("select from db");

callback(null, { cat: "Evgeniy" });
});

const getHttpPage = wrapAsync((page, callback) => {
console.log("page - ", page);
console.log("Page retrieved");

callback(null, { page: "<html>hello world!</html>" });
});

const chain = () => {
const stack = [];

const executor = () => {
let result = () => null;

const len = stack.length;

for (let i = len - 1; i >= 0; i--) {
const [fn, args] = stack.pop();

const prev = result;

result = (err, data) => {
if (err) return console.error({ err });
fn(...args, prev);
};
}

result();
};

executor.do = (cb, ...args) => {
stack.push([cb, args]);

return executor;
};

return executor;
};

const startChain = chain()
.do(readConfig, "myConfig")
.do(selectFromDb, "select * from cities")
.do(getHttpPage, {});

startChain();