how to get the value from a callback function

浪子不回头ぞ 提交于 2019-12-02 10:45:29

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.

Eventhough it will make your code a mess, you can append the variables to the window object. For example:

function a()
{
 window.testStr = "test";

}

function b()
{
 alert(window.testStr);
}

Or even create your own object, instead of using window, as such:

var MyRSSReader = {
 TitleOne : '',
 TitleTwo : '' 
} 

MyRSSReader.TitleOne = "My title";

Wikipedia has a nice article about global variables, and why they are bad.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!