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 );
});
});
}