简体   繁体   中英

Creating a call when ready function in javascript

I am relatively new to javascript and I am trying to clean up my prototype code because it's buncha deep nested levels of callbacks and it's hard to read. I am trying to achieve something like this:

GoogleMaps.ready(map_id_name, function(map) {
    g_map = map.instance;
})

...

call_when_ready(g_map, set_map_viewport);
call_when_ready(g_map, create_markers);
call_when_ready(g_map, update_icons);
call_when_ready(g_map, update_geometry_display);
call_when_ready(g_map, update_ui_display);  

I know I can move all the call_when_ready in the GoogleReady callback but this is a simplified example where call_when_ready is called in another callback.

so I came up with this function but it doesn't work:

function call_when_ready(variable, callback) {

    let interval = setInterval(() => 
    { 
        if (variable != undefined && variable != null) {
            clearInterval(interval);
            callback();
        }

    }, 3000);
}

The variable is always showing null even though g_map is being populated. How can I achieve this in a clean manner? I am open to using jQuery too but that Promise and Deffer ed seems too much for something trivial. Or maybe is there a better way for example chaining callbacks like so that I don't know about:

function().finished(function).finished(alert(""));

g_map is in the local scope of the anonymous function inside your GoogleMaps.ready call.

If I'm understanding your intention correctly you should move all your function calls into the anonymous function.

GoogleMaps.ready(map_id_name, function(map) {
    g_map = map.instance;
    set_map_viewport();
    create_markers();
    update_icons();
    update_geometry_display();
    update_ui_display();  
});

最简单的选择是将引用的函数移到GoogleMaps.ready函数中, GoogleMaps.ready ,如果我没记错的话,已经有一个回调

It works if instead of passing the variable to check, you pass a function that returns it:

 /* mockup */ var g_map; var map_id_name = "example"; var GoogleMaps = { ready: (a, f) => { f({ instance: 1 }); } } // simulate map being ready after 2.5 seconds setTimeout(() => { GoogleMaps.ready(map_id_name, function(map) { g_map = map.instance; console.log("g_map set"); }); }, 2500); function call_when_ready(getVariable, callback) { let interval = setInterval(() => { if (getVariable()) { clearInterval(interval); callback(); } }, 2000); } function getGMap() { return g_map; } call_when_ready(getGMap, set_map_viewport); call_when_ready(getGMap, create_markers); function set_map_viewport() { console.log("set_map_viewport"); } function create_markers() { console.log("create_markers"); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM