I'm trying to download several files from a server. I ran into error memory leak
with for
, forEach
and map
, so I use this callback function and it works:
.then(files => {
const downloadFile = callback => {
if (files.length > 0) {
let file = files.shift();
client.download(`/${file}`, `./${file}`, () => {
console.log(`Downloaded: ${file}`);
downloadFile(callback);
});
}
else {
callback();
}
};
downloadFile(() => {
console.log('All done');
})
})
I'd like to convert it into a Promise function
but I'm stuck, I've tried new Promise((resolve, reject)=>{})
and Promise.all()
but it only returns the first file.
You can use map()
with your files
array to produce one promise for each file. Then you can can call Promise.all()
to know when they have all been downloaded.
Since we don't know anything about your client.download()
method, we are guessing that it's doing what it should. It's strange that it's callback doesn't take a parameter with the actual file data.
let promises = files.map(file => {
return new Promise((resolve, reject) => {
client.download(`/${file}`, `./${file}`, () => {
// should this call back have some data or error checking?
console.log(`Downloaded: ${file}`);
});
})
})
Promise.all(promises)
.then(() => console.log("all done"))
Since this is happening inside another then()
you could just return Promise.all(promises)
to handle it downstream.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.