Tuesday 29 March 2016

What's the best option for storing state in this node.js module? X-post from /r/learnjavascript

Hi,I'm using the q library in node.js. Basically my code calls a series of functions, some synchronous and some asynchronous, passing the result from one function to the next. See my code at the end of this post.My problem is my code only passes the result from one function to the next function that is called. The existing setup only allows for the result of one function to be passed to the next consecutive function in the chain. I'd like to pass the result of say the first function in the chain to the third function called in the chain.What's a good approach to storing the result from calling a function so it can be passed to a function that is called several steps later in the chain, rather than having to pass the result to the next function to be called?Many thanks."use strict"; /*jslint node: true */ let Q = require('q'); let baseFunctions = { parsePage: require('./parsePage'), extractTitles: require('./extractTitles'), walkTheDom: require('./walkTheDom'), getTitles: require('./getTitles') }; let generateFunctions = (config) => { let chosenFunctions = {}; for (let funcName in config.functions) { if (baseFunctions[funcName] !== undefined) { let baseFunc = baseFunctions[funcName]; let args = config.functions[funcName].args && config.functions[funcName].args; chosenFunctions[funcName] = args ? baseFunc.bind(null, args) : baseFunc; } } let funcArr = (Object.keys(chosenFunctions).map(key => chosenFunctions[key])); return funcArr; }; let main = (config) => { let funcArr = generateFunctions(config); let result = funcArr.reduce(Q.when, Q()); result.done(function(end) { console.log(end); }); }; main({ functions: { parsePage: { args: ["http://ift.tt/22ZkQ27"] }, getTitles: { args: 'Multi-Scale Tone Mapping' }, walkTheDom: { args: null } } });

Submitted March 29, 2016 at 11:11PM by nh78

No comments:

Post a Comment