Raghu Chahar
Raghu Chahar

Reputation: 1773

Stop further execution process if client cancels request in between in NodeJs

I am creating pdf of websites using puppeteer, cheerio and pdfkit on my NodeJs server which takes lot of time, now I wanted to abort all processes if client cancels request i.e closes browser, tab etc so that server doesn't process unnecessary processes. For example:

app.get("/api/processScreenshot/:url", async (req, resp) => {
  const links = await collectAllLinks(url);
  const screenshotsPath = await takeScreenshots(links);
  const pdfPath = await createPDF(screenshotsPath);
  resp.status(200).end(pdfPath);
});

Is it possible to abort all the further processes inside this rest API if request gets cancel by any means i.e it receives cancel, close or abort event?

Upvotes: 1

Views: 1164

Answers (1)

Evert
Evert

Reputation: 99505

There is no general way to cancel any asynchronous function, so if you just see an await you will need to dive into the function to see if they have some facility to cancel the process.

For example, why is createPdf asynchronous? Maybe it calls an external process? You could kill that process. Maybe it calls a 3rd party API? Cancel HTTP request.

A good example of a promise-based API that can be cancelled is fetch, which uses AbortController. This is a good pattern to apply to your own functions too, but you need to explicitly (mostly manually) write code for this for any function you want to add cancel support to.

Upvotes: 1

Related Questions