In the code below, I am adding a value to comb, trying to use that value in an asynchronous function, and then changing the value of comb. The value of comb within request is not as desired since comb.pop() occurs multiple times before request's callback fires. After searching many questions on stack overflow, I have tried putting a closure around request that took comb as input, but that did not work. How should I go about this?
comb = [1,2,3];
arr = [10,20,30];
promises = [];
for (var i = 0; i < arr.length; i++) {
comb.push(arr[i]);
var promise = new Promise(function(resolve, reject) {
request(url, function(err, res, body) {
// use comb
if (/* comb meets certain condition */)
resolve(body);
});
});
promises.push(promise);
comb.pop();
}
Here is my attempt at using a closure, which did not work:
var promise = new Promise(function(resolve, reject) {
(function(comb) {
request(url, function(err, res, body) {
// use comb
if (/* comb meets certain condition */)
resolve(body);
});
})(comb);
});
This will work for simple types:
Objects are always passed by references so passing an object as a parameter won't copy the object. You'll need to do that manually.