最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - JavascriptNodeJS: store return value of a function into a variable - Stack Overflow

programmeradmin1浏览0评论

I'm trying to store the return value of a function into a variable but it doesn't seem to work. I have tried everything I could possibly think about.. Maybe I'm just doing something really stupid :D I'm running the code in NodeJS using express, request, body-parser and mongoose.

var requestNews = function(){
    request(";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});
});

Anyone any ideas?

Thanks for the help!

I'm trying to store the return value of a function into a variable but it doesn't seem to work. I have tried everything I could possibly think about.. Maybe I'm just doing something really stupid :D I'm running the code in NodeJS using express, request, body-parser and mongoose.

var requestNews = function(){
    request("https://newsapi/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});
});

Anyone any ideas?

Thanks for the help!

Share Improve this question asked Jul 13, 2017 at 15:02 ScacanScacan 4657 silver badges17 bronze badges 3
  • Are you sure the api is returning 200 and all of the data you're requesting? – Shahein Moussavi Commented Jul 13, 2017 at 15:09
  • requestNews is an asynchronous function. It does not return a value, but should accept a callback as a parameter, that is called with the articleObjStr once the request's response is received. – forrert Commented Jul 13, 2017 at 15:10
  • The API is working, there is no error. :) Thanks for the help. I started coding a couple of months ago and I still have a steep path ahead of me. – Scacan Commented Jul 13, 2017 at 15:24
Add a ment  | 

5 Answers 5

Reset to default 4

request is async operation and you can not assign value like that. You can use callback or promise.

Here is a snippet code on how can you achieve this using callbacks

var requestNews = function(callback){
  request("https://newsapi/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});
  });

});

Use a callback :

var requestNews = function(callback){
    request("https://newsapi/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});
      }
    });

});

You are trying to get the return value from an asynchronous method, which is not possible. In order to plete your action, you can do following:

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

var requestNews = function(req, res){
request("https://newsapi/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});
   }
  });
};

requestNews function is not returning nothing.

var requestNews = function(){

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

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

The problem is that you are retuning a value in the function that you pass to the request method, and if this is a call back, it also will not work.

If is a call back do it in this way:

var requestNews = function(onNewsRetrived){ // Use a callback here
          request("https://newsapi/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});

   });       
});

Callback function is not triggered. That's the reason undefined value is getting printed in log.

发布评论

评论列表(0)

  1. 暂无评论