Asynchronous loading and callbacks

I'm trying to load the data of another map. As I understand, this has to be asynchronous, which means that immediately after trying to load the data, the data may not actually be available. My question is, how would both wait until the data is loaded, and check if the data is loaded? I read something about needing a callback, but I don't quite understand what that is and how to use it yet.
Putting in rough words, callbacks are functions that are passed as arguments to another function, then  called upon certain event.


For example, MV Bitmap class have the onLoad() function.


If you load for example a system image, you can do something like.


bitmap = ImageManager.loadSystem('filename')


bitmap.onLoad(callbackFunction)


The callbackFunction will be called when the bitmap completely loads. (the maker calls the function onLoad when it happens, and this event will call the callbackFunction)



For loading the map data you could do something like:

Spoiler
loadMapData = function(mapId) {    
    var url = 'data/Map%1.json'.format(mapId.padZero(3))
    var map = new XMLHttpRequest();
    map.open('GET', url);
    map.onload  = function() {
// do whatever you want to do after the file is loaded
};
    map.onerror = function() { throw new Error('Failed to load: ' + url); };
    map.send();
};



If you want the game to wait the file to be loaded, you can add a condition on the Scene_Base.prototype.isReady


For example

Spoiler
_Scene_BaseIsReadyAlias = Scene_Base.prototype.isReady;
Scene_Base.prototype.isReady = function() {
    return _Scene_BaseIsReadyAlias.call(this) && this.yourCustomCondition();
};

Scene_Base.prototype.yourCustomCondition = function() {
    return _yourCustomCondition;
};

You can turn '_yourCustomCondition' true at the game initialization, turn it false when you load the file, and turn it on again on the callback function.
That helps a ton! Thanks so much!

Original thread: https://forums.rpgmakerweb.com/threads/asynchronous-loading-and-callbacks.56388/