When TypeScript generator/yield is utilized in conjunction with Express, the retrieval of data would not

Trying to incorporate an ES6 generator into Express JS using TypeScript has been a bit of a challenge. After implementing the code snippet below, I noticed that the response does not get sent back as expected. I'm left wondering what could be missing:

Main.ts

import * as routes from "./routes";

app = express();
app.use("/", routes);

Routes.ts

import { Request, Response, NextFunction, Router } from "express";
import * as Test from "./test";

const routes: Router = Router();

routes.get( "/*", ( req: Request, res: Response, next: NextFunction ) => {
  console.log( "url", req.originalUrl );
  next();
} );

// Test
routes.get( "/test/ajax", Test.ajax );

export = routes;

Test.ts file

export function *ajax(req: Request, res: Response) {
    const html: string = yield getHtml("http://www.wagamatic.com");
    res.send({
        length: html.length
    });
}

function getHtml(url: string): Promise<string> {
    return new Promise<string>((resolve) => {
        axios.get(url).then((res) => {
           resolve( <string>res.data );
        });
    });
}

Answer №1

Upon invoking the ajax function, it returns a generator without handling the request directly. Placing a console.log within the function reveals that it does not execute when making a request. To demonstrate, trying something like console.log(ajax()) shows that the return value is a generator object.

My suggestion is to utilize async/await in Typescript, as shown below:

export async function ajax(req: Request, res: Response) {
    const html: string = await getHtml("http://www.wagamatic.com");
    res.send({
        length: html.length
    });
}

If you prefer to work with generators, you can opt for a module like co or create your own async executor. For a basic example of creating an async executor in node, you can refer to this link. However, I recommend sticking to async/await.

Answer №2

The concept of yield is not being utilized correctly in your code. It seems like you are treating it similar to async/await, but I would recommend using async/await for a more user-friendly approach.

I could provide tips on how to resolve the issue, but it appears that you have not implemented yield properly in any part of your code. I suggest visiting this page to gain a better understanding and perhaps experiment with it a bit (or consider transitioning to async/await): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield

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

What's the deal with the Zod getter function?

Is it possible to create a getter function within a Zod object? For instance, in ES5 you can achieve the following: const person = { firstName: "John", lastName: "Doe", get fullName() {return `${this.firstName} ${this.lastName}`} } person.fullNam ...

Executing child processes in the Mean Stack environment involves utilizing the `child_process`

I am working on a Mean application that utilizes nodejs, angularjs and expressjs. In my setup, the server is called from the angular controller like this: Angular Controller.js $http.post('/sample', $scope.sample).then(function (response) ...

The impressive Mean.io framework integrated with the powerful socket.io technology

Looking for guidance on integrating socket.io in the Mean.io stack? I've noticed that Mean.io frequently changes their folder structure, so I'm wondering where the best place is to configure socket.io. Should I use express.io instead? I'm ...

Troubleshooting: Difficulty with Angular 2 TypeScript interface array functionality

Currently, I am developing an Angular 2 application where I aim to showcase messages by utilizing an interface and storing all the messages in an array. Below is a snippet of my TypeScript component that highlights this functionality: export class ChatCom ...

The specified route type does not comply with the NextJS route requirements, resulting in an authentication error

Recently, I have encountered an issue with NextJS routes while working on an ecommerce project. I am seeking guidance to resolve this issue, specifically related to my route.ts file which interacts with NextAuth for providers like Google. During developmen ...

Receiving 'Module not found' error in Typings on specific machines within the same project. Any suggestions on how to troubleshoot this issue?

I have a project cloned on two separate machines, each running VS2015 with Typings 1.8.6 installed. One machine is running the Enterprise version while the other has the Professional version, although I don't think that should make a difference. Inte ...

When trying to access the Nodejs http://test.dev:3000/api/profile API, I encountered an issue where there was no 'Access-Control-Allow-Origin' header for the Origin 'http://localhost:9000'

NodeJS - Angularjs Encountering a CORS Issue in NodeJS. While REST GET requests are functioning properly, I'm facing an issue with REST POST requests in nodeJS and unable to resolve it. Upon making the request, I am receiving the common error messa ...

Navigating the way: Directing all TypeScript transpiled files to the build folder

I am currently working on a project using Angular2/Typescript, and I have the tsconfig.js file below: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "target": "es5", "sourceMap": true, ...

Executing a function in the view/template with Angular 2+

Whenever a function is called in the view of an Angular component, it seems to be executed repeatedly. A typical example of this scenario can be seen below: nightclub.component.ts import { Component } from '@angular/core'; @Component({ selec ...

Achieving a successful response code of 500 after sending a request from the REST API

My express application is receiving this request: POST http://127.0.0.1:4000/users/register-user HTTP/1.1 content-type: application/json { "firstname": "fn", "lastname": "l n", "email": "& ...

Guide to Integrating Pendo with Angular 8 and Above

I'm having some trouble setting up Pendo in my Angular 8 application. The documentation provided by Pendo doesn't seem to align with the actual scripts given in my control panel. Additionally, the YouTube tutorials are quite outdated, appearing t ...

Switching from nginx to express as a reverse-proxy server

I'm looking to swap out nginx as a reverse proxy and replace it with a dynamic setup using an node js express application. This change will allow me to configure rules on the fly, enhance logging capabilities, and improve testing options. This is how ...

What is the best way to access an optional field in Typescript without causing errors?

Is there a way to dereference an optional field from an interface in the following scenario? interface Sample { key1?: Array<Obj1> } interface Obj1 { a?: Obj2; } interface Obj2 { b?: string; } const a: Sample["key1"][number][" ...

Disarrayed generic parameters in TypeScript

The title of the question may not be perfect, but it's the best I could do. Imagine a scenario where there is a function that accepts a callback along with an optional array. The callback takes an index and another optional array as parameters, and t ...

Angular displays incorrect HTTP error response status as 0 instead of the actual status code

In Angular, the HttpErrorResponse status is returning 0 instead of the actual status. However, the correct status is being displayed in the browser's network tab. ...

Encountered a bug in the findUnique function within the services of a Nest JS and Prisma project

I have a question about using Prisma with Nest. I keep encountering this error: src/modules/auth/auth.service.ts:28:63 - error TS2322: Type 'UserWhereUniqueInput' is not assignable to type 'string'. 28 const user = await this.prisma ...

JWT authentication for restricted routes

I'm currently developing an application that requires users to log in and allows them to join private groups. I have successfully implemented the login part using JWT, but I'm struggling with how to prevent users from joining private groups until ...

What is the reason behind TypeScript indicating that `'string' cannot be assigned to the type 'RequestMode'`?

I'm attempting to utilize the Fetch API in TypeScript, but I keep encountering an issue The error message reads: Type 'string' is not assignable to type 'RequestMode'. Below is the code snippet causing the problem export class ...

Getting the date from an object stored in MongoDB can be achieved by accessing the specific property

I'm developing an application that includes both chat and posts functionality. I want to display the timestamp of the most recent post in the chat. Below is a snippet from my mongoose schema for handling posts, along with an image illustrating how the ...

The output from Typescript Box results in a union type that is overly intricate to illustrate

Encountering an error while trying to render a Box: Received error message: Expression produces a union type that is too complex to represent.ts(2590) Upon investigation here, it seems that this issue arises from having both @mui/material and @react-thr ...