George W
George W

Reputation: 51

How to run a function asynchronously in Typescript?

I want to run my function asynchronously, but how do I do that?:

    checkLocation() {
        return __awaiter(this, void 0, Promise, function* () {
            while (true) {
                setTimeout(function () {
                    this.diagnostic.isLocationEnabled().then(
                        (isAvailable) => {
                            console.log('Is available? ' + isAvailable);
                            if (!isAvailable) {
                                alert('Please turn on the location service');
                            }
                        }).catch((e) => {
                            console.log(e);
                        });
                }, 5000)
            }
        });
    }
}

One of the discovered problems is that TS cannot fine name __awaiter. I have tried to follow this

Upvotes: 0

Views: 10804

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073978

As I said in the comments, __awaiter isn't something you write. It's output by the TypeScript compiler if you us async/await functions.

Re what you said you want to do:

[It] should check if the location service (on the phone) is enabled asynchronously

The check will be asynchronous regardless, because this.diagnostic.isLocationEnabled is asynchronous.

The async/await way to write checkLocation would be to make it an async method, which would consume the promise from isLocationEnabled via await:

async checkLocation() {
    const isAvailable = await this.diagnostic.isLocationEnabled();
    console.log('Is available? ' + isAvailable);
    if (!isAvailable) {
        alert('Please turn on the location service');
    }
    return isAvailable;
}

The non-async/await version of that is this using promises explicitly:

checkLocation() {
    return this.diagnostic.isLocationEnabled().then(isAvailable => {
        console.log('Is available? ' + isAvailable);
        if (!isAvailable) {
            alert('Please turn on the location service');
        }
        return isAvailable;
    });
}

Note that I've removed the catch handler, because by returning the promise you're deferring error handling to the caller.

If checkLocation is meant to be fire-and-forget rather than returning the (promise of) the flag, then you wouldn't use an async function at all and wouldn't return the promise (and so would keep the catch):

checkLocation() {
    this.diagnostic.isLocationEnabled().then(isAvailable => {
        console.log('Is available? ' + isAvailable);
        if (!isAvailable) {
            alert('Please turn on the location service');
        }
    }).catch((e) => {
        console.log(e);
    });
}

Upvotes: 2

Related Questions