Async/Await with Promise in Node Express and TypeScript 2


In this tutorial i will try to implement async/await with promise in typescript 2.

Step1: First of all we need to config for tsconfig.json

Focus on hightligth text

"compilerOptions": {
"target": "es6",
"lib": ["es2015", "es2016", "dom", "es2017", "es6", "es5"],
// "lib": ["es6", "dom"],
//"outDir": "./**/*", // use this for building out to a differen't directory'
"outDir": "./dist/build",
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"strictNullChecks": false,
"removeComments": true,
//"noUnused": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"moduleResolution": "node",
"sourceMap": true,
"inlineSources": true,
"experimentalDecorators": true
},
"include": [
//"./**/*",
"./**/*.d.ts",
"./typings/**/*"
],
"exclude": [
"./node_modules",
"./**/*.spec.ts"
],
"files": ["./app.ts"],
"typeRoots": ["./typings"]
}

Step 2: create new model object

 class Product {
public id: number;
public name: string;
public price: number;
/**
*
*/
constructor(id: number, name: string, price: number) {
this.id = id;
this.name = name;
this.price = price;
}

}
export { Product }

 

 

Step 3: Create service using promise

import { Product } from "../model-wrapper/product";
import Promise = require('promise');

export default class ProductService {
    private _products = [
        new Product(1, 'coffee', 10000),
        new Product(2, 'capuchino', 50000),
        new Product(3, 'sting', 1000),
        new Product(4, 'coca', 40000)
    ];
    public gets(): Promise<Product[]> {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(this._products);
            }, 5000);
        });
    }
    public get(id: number): Promise<Product> {
        return new Promise((resolve, reject) => {
            setTimeout( () => {
                let product = this._products.filter(t => t.id == id);
                if (product.length > 0)
                    resolve(product[0]);
                else reject(`Not found :${id}`);
            }, 5000);
        });
    }

}

 

Step 4: Create router for api and use async/await in router

import express = require('express');
import { Request, Response, } from 'express';
const router = express.Router();
import ProductService from '../services/products.service'

let productService = new ProductService();
router.get("/", async (req: Request, resp: Response) => {
    try {
        let products = await productService.gets();
        resp.json(products);
    } catch (err) {
        resp.status(500);
        resp.json(err);
    }
});

router.get("/:id", async (resq: Request, resp: Response) => {
    let id = +resq.params.id;
    try {
        let product = await productService.get(id);
        resp.json(product);
    }
    catch (err) {
        if (err.indexOf("Not found") > -1) {
            resp.status(400);
            resp.json(err);

        } else {
            resp.status(500);
            resp.json(err);
        }
    }

})


export default router;

 

Step 5: Add to root server

import products from './routes/products';

app.use('/product',products)

 

Step 6: Run your server and try to test with rest client tool

 

Hope you understand main idea in this post 😀

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.