Open pieterdt opened 5 years ago
In your example you’re pushing the return value of getDetail (which is undefined) onto the queue. An anonymous function is not the only way to close around variables, but it is one of the easiest. You could also look at Function#bind, or perhaps having the job pop or shift variables from the array at runtime.
I had to do something similar to what you are trying to achive. I solved it using closures
function createJob(id) {
return function (cb) {
console.log('do something with id = [' + id + ']');
cb();
}
}
[1, 2, 3].forEach(function (id) {
q.push(createJob(id));
});
Hi,
I'm trying to use this module, but (due to limited skills) I can't figure out how to push items to the queue with a parameter. E.g. I want to loop over an array of id's and push for every item some function into the queue that has this id as a parameter. Not sure how to approach such thing in a smart way. I think defining an anonymous function for each item in the array is not the right way forward. Ideally there is one function that defines what to do when the job is executed. But the execution should be using the id parameter for which the job was added.
Not sure if the above is clear, but I want something like
hope this is more clearly illustrates what I'm after...
Thanks for any advice.