javascript - http request function won't return result -


i setting server express.js , want 'get' request '/' return results of function. function making request news api. when make call '/', function being triggered, , results ('stories') being logged in console, nothing being sent in response '/' 'get' request. have tried putting 'return' statement in few different places , still doesn't work... idea hugely appreciated! thanks!

app.js

var express = require('express'); var app = express(); var stories = require('./stories.js')   app.get('/', function(req, res){   var returnedstories = stories.searchstories();   res.send(returnedstories); })  var server = app.listen(3000, function () {    var host = server.address().address;   var port = server.address().port;    console.log('going live on port', host, port);  }); 

stories.js

var request = require('request');     function searchstories(){   var stories = '';   request({     url:'http://content.guardianapis.com/search?q=christopher%20nolan&api-key=3th9f3egk2ksgp2hr862m4c9',     json: true},      function (error, response, body) {     if (!error && response.statuscode == 200) {       console.log(body.response.results) ;       stories = body.response.results;       return stories;     }   }) };   module.exports = {   searchstories: searchstories   } 

it's asynchronous problem. searchstories function not finish when execute res.send.

you can use promise (https://www.promisejs.org) or callback. i'll give example callback.

stories.js

module.exports.searchstories = function (callback) {   var stories;    // stories execute callback result    stories = [     {id: 1, name: "story 1"},     {id: 2, name: "story 2"}   ];    callback(stories); } 

app.js

var express = require('express'); var app = express(); var stories = require('./stories.js')   app.get('/', function(req, res){   stories.searchstories(function (returnedstories) {     res.send(returnedstories);   }); })  var server = app.listen(3000, function () {    var host = server.address().address;   var port = server.address().port;    console.log('going live on port', host, port);  }); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -