我目前正在试验信标,我想获取信标的 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/