首页 > 解决方案 > 我可以在回调本身中结束 firebase 回调吗?

问题描述

我想知道是否有任何方法可以在回调本身内停止回调。我已经尝试使用 ref.off() 方法来停止它,如下所示,但它仍会继续运行。有什么建议么?

ref.orderByChild('t').startAt(time.getTime()).on('child_added', function (snapshot) {
  const d = snapshot.val();
  const x = Math.round(d.x * 100).toString();
  const y = Math.round(d.y * 100).toString();
  if (that.selectedEnd && d.t > that.selectedEnd.getTime()) {
    snapshot.ref.off('child_added');
    console.log('STOP');
  } else {
    ....
  }
});

标签: typescriptfirebasefirebase-realtime-database

解决方案


根据 API 文档on()

返回函数

提供的回调函数未经修改返回。如果您想将内联函数传递给 on() 但存储回调函数以供稍后传递给 off(),这只是为了方便。

因此,您可以将其返回值传递给off(), 在您调用的同一 Query 对象上调用on()

const query = ref.orderByChild('t').startAt(time.getTime());
const listener = query.on('child_added', function (snapshot) {
    ...
    query.off('child_added', listener);
});

推荐阅读