How to Poll for API Request Status with JavaScript in NodeJS

Implement asynchronous pdfRest request polling with JavaScript in NodeJS and retrieve the completed operation response.
Share this page

This step-by-step guide demonstrates how to submit asynchronous document work and poll its request status from a NodeJS service through the API Polling Tool. Along the way, we'll distinguish the JavaScript in NodeJS syntax from the Poll for API Request Status API contract and show how its returned data supports the next step.

Why Poll for API Request Status with JavaScript in NodeJS?

A NodeJS service does not need to keep a long document-processing request open until the result is ready. Asking for a request ID separates submission from completion and allows other application work to continue.

Imagine an API gateway that starts a large PDF-to-image job but has a short upstream timeout. The service can return control after submission, place the request ID on a queue, and let a worker call the status route until the output or an error becomes available.

The example uses an asynchronous sleep between GET requests and stops when the reported status is no longer pending. Production logic should treat completion and failure as distinct terminal outcomes rather than assuming every non-pending response succeeded.

JavaScript in NodeJS Code Example

const axios = require("axios");
const FormData = require("form-data");
const fs = require("fs");

// By default, we use the US-based API service. This is the primary endpoint for global use.
var apiUrl = "https://api.pdfrest.com";

/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
 * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 */
//var apiUrl = "https://eu-api.pdfrest.com";

const apiKey = "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Replace with your API key
const pathToFile = "/path/to/file.pdf";


const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const sendBmpReq = async (config) => {
  return await axios(config);
};

const pollUntilFulfilled = async (requestId) => {
  const pollConfig = {
    method: "get",
    maxBodyLength: Infinity, // set maximum length of the request body
    url: `${apiUrl}/request-status/${requestId}`,
    headers: { "Api-Key": apiKey }
  };
  requestStatusResponse = await axios(pollConfig);
  let status = requestStatusResponse.data.status;

  // This example will repeat the GET request until the BMP request is completed.
  while (status === "pending") {
    console.log(JSON.stringify(requestStatusResponse.data));
    await sleep(5000);
    requestStatusResponse = await axios(pollConfig);
    status = requestStatusResponse.data.status;
  }
  console.log(JSON.stringify(requestStatusResponse.data));
};

const demoApiPolling = async () => {
  try {
    // Send a request with the Response-Type header (using /bmp as an arbitrary example)
    const bmpRequestData = new FormData();
    bmpRequestData.append("file", fs.createReadStream(pathToFile));

    const bmpConfig = {
      method: "post",
      maxBodyLength: Infinity,
      url: apiUrl + "/bmp",
      headers: {
        "Api-Key": apiKey,
        "Response-Type": "requestId", // Use this header to get a request ID.
        ...bmpRequestData.getHeaders(),
      },
      data: bmpRequestData,
    };
    bmpResponse = await sendBmpReq(bmpConfig);
    console.log(JSON.stringify(bmpResponse.data));

    // Get the request ID from the initial response.
    const requestId = bmpResponse.data.requestId;
    await pollUntilFulfilled(requestId);
  } catch (err) {
    console.error(err);
  }
};

demoApiPolling();

Source for Poll for API Request Status: View the JavaScript in NodeJS sample on GitHub.

Breaking Down the Code

Load the NodeJS request and file modules

const axios = require("axios");
const FormData = require("form-data");
const fs = require("fs");

Axios sends the HTTP calls for Poll for API Request Status, FormData constructs multipart bodies when needed, and Node's fs module opens local files as streams. Together, these packages provide the transport and file handling required by the JavaScript Poll for API Request Status sample.

Select the pdfRest service region

// By default, we use the US-based API service. This is the primary endpoint for global use.
var apiUrl = "https://api.pdfrest.com";

/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
 * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 */
//var apiUrl = "https://eu-api.pdfrest.com";

const apiKey = "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Replace with your API key

apiUrl centralizes regional routing for Poll for API Request Status. The NodeJS Poll for API Request Status flow can switch to the documented EU hostname without changing the endpoint paths that follow.

Define the asynchronous status loop

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const sendBmpReq = async (config) => {
  return await axios(config);
};

const pollUntilFulfilled = async (requestId) => {
  const pollConfig = {
    method: "get",
    maxBodyLength: Infinity, // set maximum length of the request body
    url: `${apiUrl}/request-status/${requestId}`,
    headers: { "Api-Key": apiKey }
  };
  requestStatusResponse = await axios(pollConfig);
  let status = requestStatusResponse.data.status;

  // This example will repeat the GET request until the BMP request is completed.
  while (status === "pending") {
    console.log(JSON.stringify(requestStatusResponse.data));
    await sleep(5000);
    requestStatusResponse = await axios(pollConfig);
    status = requestStatusResponse.data.status;
  }
  console.log(JSON.stringify(requestStatusResponse.data));
};

The JavaScript in NodeJS status request addresses /request-status/{requestId} and repeats while the state is pending. A production JavaScript in NodeJS Poll for API Request Status implementation should impose a deadline and handle every terminal error explicitly.

Submit the initial operation for a request ID

const demoApiPolling = async () => {
  try {
    // Send a request with the Response-Type header (using /bmp as an arbitrary example)
    const bmpRequestData = new FormData();
    bmpRequestData.append("file", fs.createReadStream(pathToFile));

    const bmpConfig = {
      method: "post",
      maxBodyLength: Infinity,
      url: apiUrl + "/bmp",
      headers: {
        "Api-Key": apiKey,
        "Response-Type": "requestId", // Use this header to get a request ID.
        ...bmpRequestData.getHeaders(),
      },
      data: bmpRequestData,
    };
    bmpResponse = await sendBmpReq(bmpConfig);
    console.log(JSON.stringify(bmpResponse.data));

    // Get the request ID from the initial response.
    const requestId = bmpResponse.data.requestId;
    await pollUntilFulfilled(requestId);
  } catch (err) {

Adding response-type: requestId changes the initial JavaScript in NodeJS processing response into an asynchronous identifier. The Poll for API Request Status operation continues normally while the JavaScript in NodeJS caller prepares its status checks.

Pass the returned ID into the poller

// Get the request ID from the initial response.
    const requestId = bmpResponse.data.requestId;
    await pollUntilFulfilled(requestId);
  } catch (err) {
    console.error(err);

The final Poll for API Request Status handling in JavaScript in NodeJS exposes the HTTP result and JSON body. Before using a Poll for API Request Status output or request ID, production JavaScript in NodeJS code should verify the status and retain the identifier required by the next step.

Beyond the Tutorial

You can now separate pdfRest submission from completion in JavaScript in NodeJS, retain the returned request ID, and retrieve the terminal response on your own schedule.

Persist the request ID with the originating job and apply a timeout or retry ceiling. This prevents an interrupted process from losing track of work and keeps an unexpected status response from creating an endless polling loop.

Try the Poll for API Request Status workflow with a representative file in API Lab, then adapt the request in JavaScript in NodeJS. The API Polling Tool documentation provides the complete JavaScript in NodeJS context for Poll for API Request Status values, defaults, and limitations.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.