First of all, I must confess, that there are dozens of similar questions here at stackoverflow (this, this and myriads of others), but all of them are nicely solved with the help of a callback function or simply putting a code inside this image.onload
event:
image.onload = function () {
//do other stuff that should be done right after image is loaded
}
But this is not my case. This is a signature of my function that is responsible for loading images:
function patternBuilder (index) {
var pattern, image, ...
...
image = new Image();
image.id = "_" + index + "_";
image.src = "images/_" + index + "_.png";
image.onload = function () {
pattern = ctx.createPattern(image, "repeat");
}
return pattern; // !!!! may return undefined if image is not yet loaded
}
So, I need to return! I must do it and I have no other chance. The reason I must follow this signature is that, this pattern is used by some external library function which looks like so:
style: function (feature) {
var pattern = patternBuilder(feature.get("index"));
var style = new ol.style.Style({
fill: new ol.style.Fill({
color: pattern
})
});
return style;
}
So, even if I can change the logic of my patternBuilder
function, I still can not change the external library function. This external function uses patternBuilder
and returns a style variable itself. So, there is no room for callbacks.