如何在Typescript中异步运行函数?

如何在Typescript中异步运行函数?,typescript,asynchronous,ionic-framework,Typescript,Asynchronous,Ionic Framework,我想异步运行我的函数,但我该如何做呢 checkLocation() { return __awaiter(this, void 0, Promise, function* () { while (true) { setTimeout(function () { this.diagnostic.isLocationEnabled().then(

我想异步运行我的函数,但我该如何做呢

    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)
            }
        });
    }
}

发现的问题之一是TS无法确定名称
\u waiter
。正如我在评论中所说,
\u waitier
不是你写的东西。如果您使用
async
/
wait
函数,它将由TypeScript编译器输出

你说你想做的就是:

[它]应该检查位置服务(在手机上)是否异步启用

无论如何,检查都是异步的,因为
this.diagnostic.isLocationEnabled
是异步的

async
/
await
写入
checkLocation
的方法是将其设置为
async
方法,该方法将通过
await
使用
isLocationEnabled
的承诺:

async checkLocation() {
    const isAvailable = await this.diagnostic.isLocationEnabled();
    console.log('Is available? ' + isAvailable);
    if (!isAvailable) {
        alert('Please turn on the location service');
    }
    return isAvailable;
}
它的非
异步
/
等待
版本明确使用了以下承诺:

checkLocation() {
    return this.diagnostic.isLocationEnabled().then(isAvailable => {
        console.log('Is available? ' + isAvailable);
        if (!isAvailable) {
            alert('Please turn on the location service');
        }
        return isAvailable;
    });
}
请注意,我已经删除了
catch
处理程序,因为通过返回承诺,您将错误处理推迟到调用方

如果
checkLocation
是指fire and forget,而不是返回(promise of)标志,那么您根本不会使用
async
函数,也不会返回promise(因此会保留
catch
):


我们无法从问题中的代码中知道为什么上面没有
\u waiter
。它与sync/async没有任何关系。
\u waiter
不是您编写的东西。如果您使用
async
/
wait
函数,它将由TypeScript编译器输出。在您的链接中:“对于上面的示例,TypeScript编译器为
ping
函数发出下面的ES6 JavaScript。”正如上面所说的,包含
\uu waiter
的代码是TypeScript编译器的输出。您希望您的函数实际做什么?您希望它异步做什么?这些代码中的哪些部分实际上是您的,而不是您在某处找到的一些样板文件?请注意,
while(true)
启动
setTimeout
而不中断循环不是一个好主意。既然不是这样,我建议您使用承诺和异步函数回到基础。找几个简单的例子,从那里开始,这将是你最后的建议。但是,如果我想让它继续运行,我能不能在
这个.diagnostic.isLocationEnabled()之前放一个while循环。然后(isAvailable=>{
?@GeorgeW:“让它继续运行”是什么意思?希望您的意思不是希望不断地向用户发出
警报
?我的意思是只要
可用
为假,它就应该一直显示警报。这是需要的,因为应用程序需要用户位置才能工作properly@GeorgeW:警报的性质是它将一直显示,直到用户将其解除。如果你是说你想反复发出
警报
,直到用户允许位置服务,这是一个非常、非常、非常糟糕的主意,因为这会妨碍用户启用位置服务,并且会激怒用户,让他们远离应用程序。相反,只需将应用程序置于一种状态,它会说它无法运行,因为它需要位置n服务,通过按钮或类似按钮,用户可以单击说“我现在已经打开了”。您将再次触发该按钮
checkLocation
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);
    });
}