http 请求函数不会 return 结果

http request function won't return result

我正在用 Express.js 设置一个服务器,我想要一个 'GET' 请求 '/' 到 return 一个函数的结果。该函数正在从新闻 API 发出获取请求。当我调用 '/' 时,该函数被触发,结果 ('stories') 被记录在控制台中,但在对 '/' [=19= 的响应中没有发送任何内容] 要求。 我已经尝试将 'return' 语句放在几个不同的地方,但它仍然不起作用......任何想法将不胜感激!谢谢!

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
  }

这是一个异步问题。 searchStories 函数在执行 res.send 时未完成。

您可以使用承诺 (https://www.promisejs.org) 或回调。我会给你一个回调的例子。

stories.js

module.exports.searchStories = function (callback) {
  var stories;

  // GET your stories then execute the callback with the 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);

});