0

Hei, i need some help, what i want is to wait for all file from url finished downloaded(writen) and than when it finish it will run another function. in this code block that i wrote, the resolve will be ran first before waiting for all file finished writing and thats not what i want.

pages argument is a array of url.

so, if i use 'finish' callback, the callback will be run for every url that finish, the thing i want to do is wait for all of the url, and than run the resolve();

function urlDownload(TITLE, PAGES) {
  const download = new Promise((resolve, reject) => {
    PAGES.map((value, index) => {
      request
        .get(value)
        .pipe(fs.createWriteStream(`folder/${TITLE}/${index}.jpg`))
        .on("finish", () => console.log(`Finished downloading ${index}.jpg`));
    });
    resolve("Done");
  });
  download.then((resolve) => {
    console.log(resolve);
  });
}
Cendy
  • 3
  • 3
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Krzysztof Krzeszewski Sep 10 '20 at 10:37
  • @KrzysztofKrzeszewski the finish call back will be run for each url, what i want is, wait for all of the url to be finished writen,thanks for quick help – Cendy Sep 10 '20 at 10:41
  • i posted an answer that will handle waiting for all of them – Krzysztof Krzeszewski Sep 10 '20 at 11:09

1 Answers1

0

Just put the resolve function call within finish callback, and wrap each request with a Promise individually

function urlDownload(TITLE, PAGES) {
    const download = Promise.all(PAGES.map((value, index) => {
        return new Promise((resolve) => request
            .get(value)
            .pipe(fs.createWriteStream(`folder/${TITLE}/${index}.jpg`))
            .on("finish", () => (console.log(`Finished downloading ${index}.jpg`, resolve("Done")))));
    }));

    download.then((resolve) => {
        console.log(resolve);
    });
}
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
  • not sure why people gave me a dislike, I just answered a question on how to create and wait for list of promises to finish, if there is a better alternative for this particular library, please let me know, instead of simply giving a `not useful` reward – Krzysztof Krzeszewski Sep 10 '20 at 11:07
  • Will check this out when im done doing my stuff, tysm. Will mark this if it work – Cendy Sep 10 '20 at 11:34