1

I'm new in Node and I've watched some of the tutorials from the Net. My main problem is how I can show the result from the route I created. Well, I'm getting the correct data using the console but when I access it through browser it doesn't show the json encoded data.

Here is my product.js:

const express = require('express');
const router = express.Router();
const connection = require('../connection');

router.get('/',(req,res)=>{
    res.send(products());
})

async function products(){
    // console.log(products)
    return await getProducts();
}

function getProducts(){
    return new Promise((resolve,reject) =>{
         connection.query('SELECT brand,description from products limit 100', function (err, rows, fields) {
            if (err) throw err
            resolve(JSON.stringify(rows))
        })
    })
}

module.exports = router;

Here is the console log result : http://prntscr.com/llxgk2

Here is the result from the postman: http://prntscr.com/llxgy3

3
  • Since you're just starting out: You're missing ; after throw err, resolve(JSON.stringify(rows)), and your query call. Automatic Semicolon Insertion will handle it for you, but you don't appear to be intentionally relying on ASI (some people do, I don't recommend it), so I thought I'd mention it. Commented Nov 23, 2018 at 8:42
  • 1
    @T.J.Crowder noted I'll always keep that on mind Commented Nov 23, 2018 at 8:51
  • 2
    your async function products() is pretty much pointless as it does nothing but forwarding a function call. You could write that function as function products(){ return getProducts() } and the behaviour would be the same. Or you just use getProducts() Commented Nov 23, 2018 at 8:54

1 Answer 1

3

You need to consume the promise. In your case, probably with then and catch handlers:

router.get('/',(req,res)=>{
    products()
    .then(products => {
        res.json(products);
    })
    .catch(error => {
        // ...send error response...
    });
});

Note I've used res.json to send the response. You probably want to change your resolve(JSON.stringify(rows)) to just resolve(rows) and leave what to do with the rows to the caller. (res.json will stringify for you.)

You might also look at Koa, which is from the same people who did Express, which provides first-class support for async functions as routes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.