node.js - 在第一次完成之前,不允许使用相同参数调用订阅者两次

标签 node.js firebase asynchronous concurrency beacon

我目前正在试验信标,我想获取信标的 RSSI 测量值,以便触发警报功能。

我的问题如下:

alarm function is triggered multiple times once the subscriber is called

我想要什么:

Do not allow alarm to execute more than once with the previous argument. For example if the alarm function is called with argument 'x' then someone cannot call alarm with 'x' but can call it with 'y' in order to avoid multiple pushes to the database.

我的代码(我使用 Nobel 作为信标,使用 firebase 作为数据库):

// alarm script

import { config, Device, db, auth, productsRef } from './index';
import * as noble from 'noble';
import * as firebase from 'firebase';


var acquiredRef = db.ref('acquired');

function condition(p) {
   // a boolean function that does something


}


function alarm (address) {
  console.log('Alarm!');
  let incident = {
    date : Date(),
    uuid : address,
  }
  db.ref('alarms').push(incident);

}

if (require.main === module) {

  noble.on('stateChange', function (state) {
    if (state === 'poweredOn') noble.startScanning([], true);
    else noble.stopScanning();
  });

  noble.on('discover', function(peripheral) {
    peripheral.address = peripheral.address.toUpperCase();

      if (condition(peripheral)) {
          // query
          acquiredRef.orderByChild('uuid').equalTo(peripheral.address).once('value')
            .then(snap => {
              if(snap.val() == null) alarm(peripheral.address);
            }).catch(err => console.log(err))
      }

  });

}

我尝试使用队列和异步锁但没有成功。它在第一次调用警报时起作用,然后具有与上面相同的行为。

提前致谢

最佳答案

如果您只想确保警报函数不会使用相同的参数(在本例中只是字符串“地址”)连续调用两次(或更多次),您可以只存储一个变量并将最近的参数与当前的参数进行比较。如果参数相同,则不执行函数的其余部分。

let previousAddress = null;
function alarm (address) {
  if (address === previousAddress) {
    return; // skip
  }
  console.log('Alarm!');
  let incident = {
    date : Date(),
    uuid : address,
  }
  db.ref('alarms').push(incident);
  previousAddress = address; // update previous argument

}

关于node.js - 在第一次完成之前,不允许使用相同参数调用订阅者两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48749519/

相关文章:

Maven 中的 Android Firebase 依赖项

java - J2EE应用程序如何实现异步处理

node.js - 使用 JSON.stringify() 和 JSON.parse() 无法获得正确的结果

android - 图片未显示在推送通知中

javascript - 部署 Meteor : Error: spawn ENOENT at errnoException (child_process. js:988:11)

android - 火力数据库 : models with Kotlin delegated properties

c# - 3 个并行任务,每个任务都在等待自己的结果

c# - 如何检查异步 Web 服务调用的错误

node.js - 为两个集合设置护照 jwt 策略

node.js - 如何从同一局域网中的远程计算机访问 Node 服务器