javascript - 这是在再次调用之前等待此函数完成的正确方法吗?(React-Native)
问题描述
我有一个监听 Firestore 数据库并实时获取一些数据的函数。然后它调用另一个函数进行计算。现在,我想知道我是否以正确的方式进行操作,因为我不希望第一个函数在第二个函数完成之前调用第二个函数。
_fetchPatientsList() {
function onResult(QuerySnapshot) { //first function
this.setState({ dataSource: QuerySnapshot });
this._calculateLocationDistance(); //second function
}
firestore()
.collection('coolection').doc().collection('public')
.where('act', '==', 1)
.orderBy('time', 'asc')
.limit(10)
.onSnapshot(onResult, onError);
}
_calculateLocationDistance = () => {
//some calculations
}
解决方案
我没有关于您正在构建的内容的完整上下文,但根据文档,只要onSnapshot
文档的内容发生变化,就会运行。这可能是也可能不是你想要的。
https://firebase.google.com/docs/firestore/query-data/listen
如果您只想保证功能的顺序,您可以这样做:
firestore()
.collection('coolection').doc().collection('public')
.where('act', '==', 1)
.orderBy('time', 'asc')
.limit(10)
.then(onResult)
.catch(onError);
或使用 async/await 语法:
try {
const result = await firestore()
.collection('coolection').doc().collection('public')
.where('act', '==', 1)
.orderBy('time', 'asc')
.limit(10)
onResult(result);
} catch (err) {
onError(err);
}
推荐阅读
- r - 如何在 Shiny 应用程序中正确使用 MutationObserve
- python-3.x - Plotly 表示不在 PyCharm SciView 中显示图
- c++ - 在运行时选择派生类并运行唯一的类方法
- php - laravel json 选择客户对象使用 hasMany 选择特定数据
- javascript - 如何通过让某人输入变量名来激活特定变量?
- javascript - 如何在nodeJS中检查与firebase db的连接
- kubernetes - 无法访问在 aws eks 中部署的服务
- python - 改进 tesseract 的图像预处理(视频游戏截图)
- c# - 无法创建“VegaDbContext”类型的对象。对于设计时支持的不同模式
- angularjs - 将 docker ARG 复制到 Angularjs 配置文件中