jagwe danfesa
jagwe danfesa

Reputation: 553

Web worker fetching data

I have webworker like below:

class FetchWorker {
    constructor(id) {
        this.id = id;
        this.ids = [];
        this.timer = 1;
    }

    start() {
        this.fetchData();
    }

    addIds(ids) {
        this.ids.push(...ids);
    }

    sendData(method, data){
        self.postMessage(JSON.stringify({
            method,
            data
        }))
    }

    fetchData() {
        this.timer *= 2;
        console.log(this.id,') ### this', this);
        console.log(this.id,') ### ids', this.ids);
        console.log(this.id,') ### FetchData', this.ids.length, this.timer);
        console.log(this.id,') ######');

        if(!this.ids.length) {
            setTimeout(this.fetchData, this.timer);
            return;
        }

        console.log(this.id, ')FETCHED ...');

        this.sendData('webworker:fetchedAds', this.ids);
        this.sendData('webworker:timer', this.timer);

        setTimeout(this.fetchData, this.timer);
    }
}

const id = Number.parseInt((Math.random() * 100) + '');

console.log('self', self);

const worker = new FetchWorker(id);

self.addEventListener('message', (event) => {
    const message = JSON.parse(event.data);
    const {method, data} = message;

    if (method === 'webworker:addids') {
        worker.addIds(data);
    }

    if (method === 'webworker:startFetching'){
        worker.start();
    }
});

I am creating this worker and send to him message with ids and with start command, but i get error in fetchData method when i try to write length of ids Array to console, error is Cannot read property length of undefined,

I checked it and this in my fetchData method pointing to DedicatedWorkerGlobalScope instead of FetchWorker class, it's a bit confused for me because i don't know why this doesn't exists in class method

Upvotes: 0

Views: 1520

Answers (1)

jagwe danfesa
jagwe danfesa

Reputation: 553

I solved my problem by bind this to fetchData in setTimeouts and it is look like:

setTimeout(this.fetchData.bind(this), this.timer * 1000);

I don't know why i had to do that

Upvotes: 2

Related Questions