I’m struggling to wrap my head around the javascript async/sync concepts.
I’ve subclassed an openlayers Layer class for some custom rendering in a map. After instantiating an object of the class, I want to load data (a png file from an url) and save the data into a class variable before I go on and do some custom webgl rendering based on the data. I’ve tried all sorts of stuff now with awaits and thens, but unable to get something to work. I was hoping someone could give me some pointers on how I should structure code to achieve this.
I’m able to do it when I load the data outside the class, but then only with a fixed url, and I need to be able to change the url on certain events.
Code for instantiating object and trying to run the function that sets the data in a class variable:
function update_map(time_change_event) {
const new_url = 'www.example.com/' + time_change_event.detail.key
const canvasLayer = new CanvasLayer({})
canvasLayer.getData(new_url)
map.addLayer(canvasLayer)
map.removeLayer(*oldlayer*)
}
Code for custom class:
export class CanvasLayer extends Layer {
data = null;
getData(url){
async data_promise = new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
const data = context.getImageData(0, 0, width, height);
resolve(data);
};
image.onerror = () => {
reject(new Error('failed to load'));
};
image.src = url;
})
this.data = await data_promise;
}
render(frameState, target){
// This is called when layer is added to map
// Doing stuff with this.data does not work because it is null
console.log(this.data) returns null
}
}