Reputation: 7026
I'm trying to make an app that donwload images from a remote server and create a slideshow from these images. The slideshow part I have sorted out. My code doesn't work because I'm trying to use the images while they are not fully downloaded. I know I need to use promises but I can't sort it out. I'm doing something wrong and I feel it's better to ask a question here on SO instead of wasting hours to figure this out.
var fs = require('fs')
var request = require('request-promise');
function downloadImgs(imageurls){ //imageurls is an array of urls
var tempar=[];
var promises=[];
for (var i = 0; i <=imageurls.length; i++) {
if(typeof imageurls[i] !== "undefined"){
img=tempfolder+i+'.jpg'; //tempfolder is a global variable
tempar.push(img);
prom=request(imageurls[i]).pipe(fs.createWriteStream(img));
promises.push(prom);
}
}
Promise.all(promises).then(function(data) {
createslideshow(tempar);//create slideshow with downloaded images
});
};
Upvotes: 2
Views: 1806
Reputation: 19617
You can't chain .pipe(...).then(...)
, because pipe
doesn't return a promise. Instead you need to use the following:
...
let req = request(imageurls[i]);
req.pipe(fs.createWriteStream(img));
promises.push(req);
Upvotes: 2