Javascript / NodeJS:将函数的返回值存储到变量中

时间:2017-07-13 15:02:08

标签: javascript node.js function variables express

我正在尝试将函数的返回值存储到变量中,但它似乎不起作用。 我已经尝试了一切我可能想到的......也许我只是在做一些非常愚蠢的事情:D 我正在使用express,request,body-parser和mongoose在NodeJS中运行代码。

var requestNews = function(){
    request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){
    if (!error && response.statusCode == 200){
        var parsedData = JSON.parse(body);
        var title       =  parsedData.articles[randomNum].title;
        var description =  parsedData.articles[randomNum].description;
        var url         =  parsedData.articles[randomNum].url;
        var urlToImage  =  parsedData.articles[randomNum].urlToImage;
        var publishedAt =  parsedData.articles[randomNum].publishedAt;
        var articleObj  = {
            title: title, 
            description: description, 
            url: url, 
            urlToImage: urlToImage, 
            publishedAt: publishedAt

        };
        articleObjStr = JSON.stringify(articleObj);
        return articleObjStr;
    }
});
};


app.get("/index", function(req, res){
    var randomNew = requestNews();
    console.log(randomNew); // LOGS UNDEFINED
    res.render("index", {randomNew: randomNew});
});

任何想法?

感谢您的帮助!

5 个答案:

答案 0 :(得分:4)

请求是异步操作,您无法分配这样的值。您可以使用callbackpromise

以下是一个代码段代码,介绍如何使用回调实现此目的

var requestNews = function(callback){
  request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){
    if (!error && response.statusCode == 200){
      var parsedData = JSON.parse(body);
      var title       =  parsedData.articles[randomNum].title;
      var description =  parsedData.articles[randomNum].description;
      var url         =  parsedData.articles[randomNum].url;
      var urlToImage  =  parsedData.articles[randomNum].urlToImage;
      var publishedAt =  parsedData.articles[randomNum].publishedAt;
      var articleObj  = {
        title: title, 
        description: description, 
        url: url, 
        urlToImage: urlToImage, 
        publishedAt: publishedAt

      };
      articleObjStr = JSON.stringify(articleObj);
      callback(null, articleObjStr);
    } else {
      callback(error)
    }
  });
};


app.get("/index", function(req, res, next){
  requestNews(function(err, data) {
    if (err) return next(err);
    console.log(data);
    res.render("index", {randomNew: data});
  });

});

答案 1 :(得分:2)

使用回调:

var requestNews = function(callback){
    request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){
    if (!error && response.statusCode == 200){
        var parsedData = JSON.parse(body);
        var title       =  parsedData.articles[randomNum].title;
        var description =  parsedData.articles[randomNum].description;
        var url         =  parsedData.articles[randomNum].url;
        var urlToImage  =  parsedData.articles[randomNum].urlToImage;
        var publishedAt =  parsedData.articles[randomNum].publishedAt;
        var articleObj  = {
            title: title, 
            description: description, 
            url: url, 
            urlToImage: urlToImage, 
            publishedAt: publishedAt

        };
        articleObjStr = JSON.stringify(articleObj);
        return callback(null, articleObjStr);
    } else {
      return callback(error);
    }
});
};


app.get("/index", function(req, res){
    requestNews(function(err, data){
      if(err) console.log(err);
      else {
        var randomNew = data;
        console.log(randomNew); // LOGS UNDEFINED
        res.render("index", {randomNew: randomNew});
      }
    });

});

答案 2 :(得分:1)

您正在尝试从异步方法获取返回值,这是不可能的。为了完成您的操作,您可以执行以下操作:

app.get("/index", function(req, res){
     requestNews(req, res);
});

var requestNews = function(req, res){
request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){
if (!error && response.statusCode == 200){
    var parsedData = JSON.parse(body);
    var title       =  parsedData.articles[randomNum].title;
    var description =  parsedData.articles[randomNum].description;
    var url         =  parsedData.articles[randomNum].url;
    var urlToImage  =  parsedData.articles[randomNum].urlToImage;
    var publishedAt =  parsedData.articles[randomNum].publishedAt;
    var articleObj  = {
        title: title, 
        description: description, 
        url: url, 
        urlToImage: urlToImage, 
        publishedAt: publishedAt

    };
    articleObjStr = JSON.stringify(articleObj);
   // return articleObjStr; do not return value from here it can not be retrived
   res.render("index", {randomNew: articleObjStr});
   }
  });
};

答案 3 :(得分:0)

requestNews函数没有返回任何内容。

var requestNews = function(){

      // Missing return Here.
      return request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){

      // All you code here.    
      return articleObjStr;
    }
  });
};

问题是您正在重新传递给传递给请求方法的函数中的值,如果这是一个回调,它也将无法工作。

如果是回叫,请以这种方式进行:

var requestNews = function(onNewsRetrived){ // Use a callback here
          request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){

      onNewsRetrived(articleObjStr); // Trigger your call back get you got the info.
    }
  });
};

app.get("/index", function(req, res){
   requestNews(funtion(randomNew) {

    console.log(randomNew); // Should Work
    res.render("index", {randomNew: randomNew});

   });       
});

答案 4 :(得分:0)

不会触发回调功能。这就是未定义值在日志中打印的原因。