首页 > 解决方案 > 这是在再次调用之前等待此函数完成的正确方法吗?(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
}

标签: javascriptfunctionreact-nativeasynchronousasync-await

解决方案


我没有关于您正在构建的内容的完整上下文,但根据文档,只要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);
}


推荐阅读