express not resolving async callback

Exploring the concept of promises further, I decided to create a simple async delay function that incorporates a timeout feature:


const app = express();

function timeout(duration) {
  return new Promise((resolve, reject) =>
    setTimeout(() => {
      console.log('timeout complete');
      resolve('promise returned');
    }, duration)
  );
}

async function delay(duration) {
  let returnedPromise = await timeout(duration);
  console.log(returnedPromise);

}

app.get('/', (req, res) => {
  res.send(`Performance example: ${process.pid}`);
});


app.get('/timer', async (req, res) => {
  await delay(5000);
  res.send(`Ding ding sing! ${process.pid}`);
});

console.log('Worker process initiated.');
app.listen(3000);

The function works as intended and responds after a 5-second delay.

However, when I modify the app.get('/timer') route in this way, the promise remains unresolved:

app.get('/timer', (req, res) => {
  async () => {
    await delay(5000);
    res.send(`Ding ding ding! ${process.pid}`);
  };
});

I am puzzled by why moving the async keyword from outside the callback to within the callback causes this issue.

EDIT:

I forgot to invoke the function :) The correct implementation is as follows:

app.get('/timer', (req, res) => {
  (async () => {
    await delay(5000);
    res.send(`Ding ding ding! ${process.pid}`);
  })();
});

Answer №1

You don't have to include that additional function in your modification because you can simply achieve the same thing with this code:

app.get('/timer', async (req, res) => {
    await delay(5000);
    res.send(`It's time! ${process.pid}`);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bringing in d3js into Angular 2

Is there a way to successfully import d3js into an Angular2 project? I have already installed d3js using npm and added it to my systemJs, but am encountering a traceur.js error. I also attempted to just use the latest cdn in a script tag and tried import * ...

Implement socket.io within expressjs routes instead of the bin/www file

Currently, I am utilizing socket.io within my expressJS application. I have established a socket connection in the bin/www file. My goal is to send data to the client side using socket.emit() in the sendmessage.js file when data is sent to it. bin/www ...

Exploring ways to run tests on a server REST API using testem

When using Testem, I have a config option called serve_files that handles serving the client-side code for me. However, I also need to run my server because it includes a REST API that the client side relies on. Is there a way to configure Testem to launc ...

Setting up Babel to effectively function across multiple directories

I've been utilizing Babel for some time now and it effectively transforms my ES Next code to the dist directory using this command: babel src --out-dir dist --source-maps --copy-files Up until now, all my JavaScript code has been stored in the src fo ...

How to efficiently transfer data between Node and Angular 7 using Electron

After setting up an Angular 7 application running on http://localhost:4200, I developed a Node JS application responsible for authenticating users on Facebook, accessible at http://localhost:3000. The callback redirection functions correctly within the No ...

Leveraging datatable in node.js applications

I'm attempting to integrate jquery Datatable with Node.js and here is the HTML code snippet I have: <button id="btnSearch" type="submit" class="btn btn-responsive"><i class="icon-search"></i>&nbsp;Search</button> <div ...

No image is displayed when searching for a photo on Google Places

When calling the API to retrieve an image, instead of getting the actual image, I receive a link to an HTML page with the requested image. How do I get only the image itself? Here is the code snippet, where the "foto" parameter is the photo_reference obtai ...

NESTJS does not have any impact on enabling CORS

I am facing issues with enabling CORS for testing purposes in the latest version of NestJS 8.0.6 on a fresh http + ws project. I need to have the Access-Control-Allow-Origin header in the server's response for the client to accept it. I have tried thr ...

The installation of NPM packages is failing when attempted with npx

I've encountered an issue while working on a CLI application using NPM. After packaging the application and trying to run it, I'm getting the following error: > npx -y [organization]-[package]-0.0.1.tgz node:internal/errors:496 ErrorCaptur ...

What steps should I take to make the image appear on the browser?

I am having trouble displaying an image on a webpage in the browser. Despite using the correct path to the image, only the alt tag is being shown along with an ordered list below it. Strangely, Visual Studio Code suggests files while building the path in t ...

I am encountering an issue when trying to containerize a Node.js application with MongoDB using Docker

Here are the Docker Compose codes I am using: version: '3' services: mongo: container_name: "mongo" image: "mongo:4.4.8" ports: - "27017:27017" web: image: docker-node-mongo build: . command: "node src/index.js" ...

Set up a new account using a RESTful API

Looking to establish a secure API using node.js for my mobile application. The goal is for users to sign up through the app with their email and password. I'm contemplating the best approach, which ideally looks something like: curl -d '{"email" ...

Adding properties to a class object in Javascript that are integral to the class

Recently, I've been contemplating the feasibility of achieving a certain task in JavaScript. Given my limited experience in the realm of JavaScript, I appreciate your patience as I navigate through this. To illustrate what I am aiming for, here' ...

Installing npm without the need for Node.js can be achieved

Looking to set up an ASP.NET Core Web Application in Visual Studio 2015 and have plans to incorporate AngularJs2 with TypeScript editing. To make this work, I need to set up the npm Package Manager. Ideally, I want to install npm without node as I will n ...

npm windows installation proxy problem

When setting up a proxy on Windows 7, I am using the following commands: npm config set proxy http://<username>:<password>@<proxy-server-url>:<port> npm config set https-proxy http://<username>:<password>@<proxy-serv ...

The webpack-concat-text-plugin "node" is not compatible

The concat-text-webpack-plugin is located deep within a package, and it throws errors when I have NextJS and Node 18. Error: The engine "node" is incompatible with this module. Expected version ">=8 <=16". Got "18.16.0" Error Found incompatible modul ...

What is the process for storing public and private keys in a file with node.js crypto?

I am working with the crypto module in node.js and have successfully generated a public/private key pair. However, I am facing an issue when trying to save it to a file and then load it back into memory from that file. Here is what I have so far: https:// ...

Having trouble with passing the callback for nested mysql queries in Async.waterfall?

I am facing an issue with my nested MySQL queries where async.waterfall is not working as expected. The second step of the waterfall is failing to append its result to the array: async.waterfall([ function(callback) { connection.query(query, function( ...

The HTTP GET request is failing to trigger

I'm currently working on building a basic messageboard using MongoDB, Angular, NODE.js and Express. Oddly enough, everything works fine the first time I call getMessages(). But when I try to call getMessages() after posting a message with postMessage ...

Encountered an issue when trying to proxy to the Node.js/Express Socket.IO server with Next.js

I'm currently facing an issue with establishing a connection between my Next.js/React client and my Express/Socket.io backend (not running as a Next.js custom server). When I attempt to proxy regular HTTP requests using rewrites in the next.config.js ...