What is the correct way to make async calls in NodeJs app

Hi,

I am using webservice with Node environment on render.com, I am making an async call in a cron job, like the below, the deploy fails after some time, am I doing this correctly ?

My Code in app.js

const cron = require("node-cron");

// Define the task to be run on a cron schedule
const task = () => {
  console.log("Cron job running at:", new Date().toLocaleString());
  // Add your cron job logic here
  asyncCall();
};

// Schedule the task to run every minute
cron.schedule("* * * * *", task);

// Log a message when the app starts
console.log("Cron job app started.");

function resolveAfter2Seconds() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("resolved");
    }, 2000);
  });
}

async function asyncCall() {
  console.log("calling");
  const result = await resolveAfter2Seconds();
  console.log(result);
  // Expected output: "resolved"
}

App Settings are as follows:
Environment: Node
Build command: npm install
Start command: npm start

package.json

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dayjs": "^1.11.0",
    "dotenv": "^16.0.0",
    "express": "^4.18.2",
    "mongodb": "^4.3.1",
    "mongoose": "^7.0.1",
    "node-cron": "^3.0.2",
    "nodemon": "^2.0.21",
    "onesignal-node": "^3.3.0"
  }
}

Hi,

Web Services are for web servers, e.g. Express, etc.

If you want to cron something, there are Cron Jobs. Or if you want to roll your own, Background Workers

Alan

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.