how to get the value from a callback function

后端 未结 2 1729
一个人的身影
一个人的身影 2021-01-27 06:58

I am relatively new to javascript and I am facing some difficulty.I have two java script files as I have shown below. I am having trouble getting the value of the variable

2条回答
  •  长情又很酷
    2021-01-27 07:20

    Seeing as it's a different scope, you can either return it in a callback, or provide it in another way such as exporting it to a higher scope that is visible to your desired location. In this case, it's the global scope, so I'd advise against that.

    function getRss(url, callback) {
    //...
    function feedLoaded(result) {
        if (!result.error) {
            var entry = result.feed.entries[0];
            var entry_title = entry.title; // need to get this value
            callback && callback(entry_title);        
        }
    }
    

    and call it like so,

    function get_rss1_feeds() {
        var Rss1_title = getRss("http://yofreesamples.com/category/free-coupons/feed/?type=rss", function(entry_title) {
            // This scope has access to entry_title
        });
    }
    

    As an aside, use your setTimeout like so:

    setTimeout(get_rss1_feeds, 8000);
    

    rather than

    setTimeout("get_rss1_feeds()", 8000);
    

    as the latter uses eval, whereas the former passes a reference to the function.

提交回复
热议问题