Im writing a function that batch downloads images with the request package. The downloading part works, but i'm having issues with passing the parameters into the Promise array.
function downloadImages(data) {
var promises = [];
var promise, local, id, url;
for (var i in data) {
(function(i) {
local = "public/images/".concat(data[i].id, ".png");
url = data[i].img_url
id = data[i].id
promise = request.get({
url: url,
local: local,
id: id,
encoding: 'binary'
}, function(err, res) {
if (!err && res.statusCode === 200) {
fs.writeFile(local, res.body, {
encoding: 'binary'
}, (err) => {
if (!err) {
doSomething()
} else {
console.log("Error Downloading image")
}
})
}
})
promises.push(promise)
})(i)
}
Promise.all(promises);
}
When I run this, all parameters in the array resolve to the last entry, so it's downloaded (data.length) times.
I've tried a couple of things but cant get any closer to a solution. Is there something fundamental im doing wrong or something rather simple? Would be very thankful for some help!