0

I am using npm Express and Request modules to obtain movie information via an API:

var express = require("express");
var app = express();
var request = require("request");

app.get("/results", function(req, res){
    console.log(getBody("http://www.omdbapi.com/?s=The+Shining&page=1&apikey=myKey"));
});

function getBody(requestString){
    request(requestString, function(error, response, body){
        return body;
    };
}

I removed error checking on the request here for the sake of readability.

Within the request, logging "body" shows that the request did return proper JSON. However, when I return to app.get, the value of the logging is undefined.

Is it not possible to return this value to app.get's callback function?

1 Answer 1

1

request is an async function, so you need to use one of the many techniques (callback, promise etc) to return the data successfully.

Here's an example with a callback:

app.get("/results", function(req, res) {
  getBody(endpoint, function (data) {
    console.log(data);
  });
});

function getBody(endpoint, callback) {
  request(endpoint, function(error, response, body) {
    callback(body);
  });
}

And an example using a promise:

app.get("/results", function(req, res) {
  getBody(endpoint).then(function (data) {
    console.log(data);
  });
});

function getBody(endpoint, callback) {
  return new Promise(function (resolve, reject) {
    request(endpoint, function(error, response, body) {
      if (error) reject('Request failed');
      resolve(body);
    });  
  });
}
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.