Search code examples
javascriptprogressive-web-appswebapi

PeriodicSyc: How to resolve the pending promise?


I want to implement a background sync using the webapi and I will need a couple of different implementations of it for specific background tasks like sync, update check and other things. My idea was to create a class BackgroundManager where I could implement the WebApi and make my implementations inherit from it.

With this code, I can create an instance of the Update class that inherits the subscribe, unsubscribe and getSubscriptions from BackgroundManager. The problem is that I cannot get a resolved promise, and I don't understand why.

Creating a update instance of BackgroundManager

class BackgroundManager {

    async subscribe() {
        const registration = await navigator.serviceWorker.ready;
        const type = this.type;

        try {
            await registration.periodicSync.register(type, {
                minInterval: this.interval,
            });
        } catch {
            console.log('Periodic Sync could not be registered!');
        }
        return 'subscribed'
    }

    async unsubscribe() {
        const type = this.type;

        const registration = await navigator.serviceWorker.ready;
        if ('periodicSync' in registration) {
            await registration.periodicSync.unregister(type);
        }
        return 'unsubscribed'
    }

    async getSubscriptions() {
        const registration = await navigator.serviceWorker.ready;
        if ('periodicSync' in registration) {
            const tags = await registration.periodicSync.getTags();
            return tags;
        }
    }
}

class Update extends BackgroundManager{
    constructor(type) {
        super();
        this.type = type;
        this.interval = 24 * 60 * 60 * 1000;
    }

    update() {
        this.id = 'updating';
    }
}

Solution

  • Periodic background sync, as currently implemented in Chrome, has a few preconditions, described in this article:

    If either of those conditions are not met, that might explain why you're having trouble using the feature.