-1

I am creating an API with ExpressJS and NodeJS, trying to wrap my head around callback. Somehow Callback is not returning the request result when called via Postman API. What might be the issue

router.get('/products', PipedriveController.pipedriveAllProducts)

// Export the router

module.exports = router;

var request = require('request');
var results;

function logRes(){
    console.log(results);
    return results
  }


function readResult(callback){
request('https://jsonplaceholder.typicode.com/posts/1', function(err, response, body){
    results=body;
    callback();
});
}


exports.pipedriveAllProducts = function(req, res, next){
    // let family = req.param.options;

    try {


        let all_products = readResult(logRes)



        //  Return All product liist with Appropriate HTTP header response
        return res.status(200).json({status: 200, all_products});
    } catch(e){

        // Return an Error Response Message
        return res.status(400).json({status: 400, message: e.message});
    }


}

My Postman API output when i consume the API,

Result:

{
    "status": 200
}

I should be expecting status 200 & the API JSON output

Cœur
  • 37,241
  • 25
  • 195
  • 267
KAKAK
  • 879
  • 7
  • 16
  • 32
  • res.json({status: 200, all_products}); – Joe Warner Apr 10 '18 at 15:03
  • Either send the data in the callback function or use async/await, promises or anything else. You can't return from an async operation like this – Luca Kiebel Apr 10 '18 at 15:04
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Luca Kiebel Apr 10 '18 at 15:05

2 Answers2

1

You have to manage the async call, you can do that with a javascript Promise :

function readResult() {
    return new Promise((resolve, reject) => {
        request('https://jsonplaceholder.typicode.com/posts/1', (err, response, body) => {
            if(err) reject(err);

            resolve(body);
        });
    });
}

exports.pipedriveAllProducts = function(req, res, next) {
    readResult()
        .then(
            products => res.status(200).json(products),
            err => res.status(404).json(err)
        ).catch(err) { res.status(500).send('Unexpected server error') }
}

I use arrow function here to have a more readable code.

If you want more information about Promises : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise Or arrow funtion: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Antoine Amara
  • 645
  • 7
  • 11
0

Provided that other part of your application is working fine this is the change you should do here

router.get('/products', PipedriveController.pipedriveAllProducts)

// Export the router

module.exports = router;

var request = require('request');



function readResult(callback){
 request('https://jsonplaceholder.typicode.com/posts/1', function(err, 
   response, body){
    callback(err, body);
 });  
}


 exports.pipedriveAllProducts = function(req, res, next){
   // let family = req.param.options;


    readResult(function(err, result){
       if(err){
          return res.status(400).json({status: 400, message: e.message});
             }else{
             return res.status(200).json({status: 200, all_products});
              }
    })

}


}

You should try to do it using more recent node libraries like async await or promises.

Mustafa Mamun
  • 2,591
  • 2
  • 14
  • 17