Reputation: 21
I'm looking for a way to take an array of values, and generate an array of functions with the argument of said function being populated by each initial array item. For example...
const IDs = [001, 002, 003]
const getEmpData = (id) => { fetch(`companysite.com/data/user eq '${id}'`) }
// Code to generate below array
[
fetch(`companysite.com/data/user eq '001'`),
fetch(`companysite.com/data/user eq '002'`),
fetch(`companysite.com/data/user eq '003'`)
]
This is a very simplified version of a problem I'm trying to solve, which may not even be the ideal thing to do - but I was curious if this was an actual pattern. I would take the resulting array, chunk it, and then put it into a reduce method to make batches of API requests.
Upvotes: 2
Views: 41
Reputation: 168913
If you don't actually need code but just an array of functions, you can use Function.bind
:
const IDs = [001, 002, 003];
const getEmpData = (id) => fetch(`companysite.com/data/user eq '${id}'`);
const getters = IDs.map(id => getEmpData.bind(null, id);
Now getters
will be an array of functions that accept no arguments and return the fetch
promise.
And if what you actually need is an array of promises you want to resolve to results, you can use Promise.all(IDs.map(getEmpData))
...
Upvotes: 0
Reputation: 1197
console.log
in below to required functionconst IDs = [001, 002, 003]
// returns a function which can be invoked lazily when needed
const getFunction = (someData) => () => console.log(someData);
// the array of functions for all `IDs`
const functions = IDs.map(x => getFunction(x));
// optionally running all the `functions`
// replace forEach with `map` if you wish to collect the resultant array from the function invocations
functions.forEach(functionToRun => functionToRun());
Upvotes: 1