javascript - React Native - 异步等待的问题
问题描述
我有 2 个函数调用:
const result = _checkPermissions();
if (result === 'granted') {
this._googleSignIn();
}
我想_checkPermissions()
在运行 if 语句之前返回.....但是我似乎无法做到这一点,代码只是继续执行 if 语句之前_checkPermissions()
返回。
我知道它与异步等待有关,但我无法弄清楚
下面是代码_checkPermissions()
export const _checkPermissions = async () => {
const result = await check(
Platform.select({
android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
}),
);
switch (result) {
case 'blocked':
return 'blocked';
case 'granted':
return 'granted';
解决方案
你只需要等待_checkPermissions
。因为它_checkPermissions
是一个async
函数,它返回一个承诺,该承诺在稍后的时间点解决/拒绝。您可以将 await 与 Promise 一起使用,也可以在 Promise.then
块内写入。
承诺方法:
const result = await _checkPermissions();
if (result === 'granted') {
this._googleSignIn();
}
- 如果你正在使用
await
你需要添加async
到父函数。*
.then
方法:
_checkPermissions().then(result => {
if (result === 'granted') {
this._googleSignIn();
}
})
推荐阅读
- json - 使用混合类型和可能的子结构快速解码 JSON
- javascript - 如何以contact7形式将类定位并添加到textarea?
- php - 每 10 次执行一次动作
- ios - 动画着色器值
- antd - 自动完成功能滞后
- python - os.scandir() 在循环中为 find() 创建问题
- amazon-web-services - 使用 boto3 为 IAM 用户授予 aws 控制台管理访问权限
- apache-camel - Junit for apache camel 多个匿名内部类处理器
- python-3.x - 仅索引 ElasticSearch 映射中的几个字段
- python - 如果同一行存在于另一个数据框中但最终都来自两个 df 的所有列,如何从 Pandas 数据框中删除行