Monday, 15 May 2017

Reusing values from asynchronous callback

So I am building an application in Node.js and express, where I have a router and API module, from which I make HTTP request. I am struggling with wrapping my head around passing values between callbacks.

It looks like this:

Router:

var dataAPI = require('../API/getData');
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) { 
        dataAPI.getData(function(res, data){
                res.render('index', {data: data});
        });
});

module.exports = router;

And the getAPI file has this function:

var request = require('request');
var config = require('../config/config');

getData = function(callback){
    request({
        headers: {
            'Content-Type' : 'application/json',
            'Authorization' : config.authorization.token
        },
        uri: config.url.get_portfolio,
        method: 'GET',
        rejectUnauthorized: false,
    }, function(err, res, body){
        if (err || body == undefined ){
            console.log("Error in first callback.");
            throw err;
        } 
        console.log("HTTP: ", res.statusCode, " GOT DATA: ", body);
    });
}

What I want to accomplish here is to be able to do

res.render('index', {data }) 

And use the data from request made in getData function. What is the correct way to do that?



via Andrew Pomorski

No comments:

Post a Comment