Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

javascript - Take array of values and defined function and generate an array of functions with each containing the respective values

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.

question from:https://stackoverflow.com/questions/65849877/take-array-of-values-and-defined-function-and-generate-an-array-of-functions-wit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • replace the console.log in below to required function

const 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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...