0

I am trying to create a function that return a REST API response using nodeJS and express, request. This is a snippet of my code:

var express = require('express')
var httpRequest = require('request');
var bodyParser = require('body-parser');
var app = express() 

function getData1() {

    request('http://www.my-server.com/data', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        return body;
      }
    })
} 

app.get('/get-data', function (request, response) {
    var data1 = getData1();

    //do something with data


  response.send(data1);
});

Would you have any idea how I can do ?

Best regards

Amine Hatim
  • 237
  • 2
  • 7
  • 19
  • You can't return from an asynchronous function without passing a callback as a parameter for it to execute and pass the response. – Joshua Jan 27 '17 at 10:29
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – chridam Jan 27 '17 at 10:41

2 Answers2

1

Since getData1 contains a asynchronous function which only returns the data when it's finish just pass a callback function into it which you will call when the asynchronous function finished

// callback -> the function you will call later
function getData1(callback) {

    request('http://www.my-server.com/data', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        // call the function when the function finishes and also passed the `body`
        return callback(body);
      }
    })
} 


app.get('/get-data', function (request, response) {
    getData1(function(data1) {
        //do something with data
        response.send(data1);
    })
});
Beginner
  • 4,118
  • 3
  • 17
  • 26
1

Always use callbacks in NodeJS

Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.

Following code will work. You were trying to access some data which REST API hasn't even returned, so callbacks will make sure that some part of the code will only run when REST API has given you some response.

const express = require('express')
const httpRequest = require('request');
const bodyParser = require('body-parser');
const app = express() 

app.get('/get-data', function (request, response) {
  getDataFromRest(function(dataFromRESTApi) {
    if(dataFromRESTApi === null) {
      return;
    }
    response.send(dataFromRESTApi);
  });
});

function getDataFromRest(callback) {
    request('http://www.my-server.com/data', function (error, response, body) {
      if (error || response.statusCode !== 200) {
        callback(null);
        return;
      }
      callback(body);
    })
} 
Mukul Jain
  • 1,121
  • 11
  • 24