I want to get the following workflow:
- Get URL of some images
- Pass those URL to another method to download them, and return the downloaded paths
- Use those paths to get the images and create a PDF file using pdfkit
After a lot of tinkering, my code looks like this -
nightmare
.goto(url)
.wait('body')
.evaluate( ()=>document.querySelector('body').innerHTML)
.end()
.then((response) => {
return getJSONData(response);
})
.then((data) => {
return processJSONData(data);
})
.then((pages) => {
return createFile(pages);
})
.catch(err => {
console.log(err);
});
getJSONData(data)
uses cheerio to parse the HTML, and processJSONData(data)
uses image-downloader to download the images. From my understanding, since this is a promise chain, it means the execution inside each then() will be asynchronous, but the then() blocks themselves will be executed sequentially. On running the code, I see that even though the first two then() blocks are executed sequentially (up to now), the createFile(pages)
block is executed immediately thereby creating a corrupt PDF file. What could possibly be the reason behind this? How can I ensure that the then()
blocks are executed synchronously, i.e. each then()
runs only after the previous then is resolved?
The complete code can be found here.