我需要减少存储在Firebase实时数据库中的计数器(名称为 credits )。
我要像这样递减计数器:
var ref = admin.database().ref('licenseCredits/' + name + '/credits');
ref.transaction( (value) => {
if (value === null) {
return 0;
} else if (typeof value === 'number') {
return value - 1;
} else {
console.log('The counter has a non-numeric value: ');
}
});
信用字段已正确减小。 我将这段代码放入了一个可调用函数中,但是我不知道如何将减小的值返回给调用者。如果仅返回ref.transaction结果,则会收到“未处理的RangeError异常”。
答案 0 :(得分:1)
根据下面的文档,应该实现一个onComplete函数。
https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction
var ref = admin.database().ref('licenseCredits/' + name + '/credits');
ref.transaction( (value) => {
if (value === null) {
return 0;
} else if (typeof value === 'number') {
return value - 1;
} else {
console.log('The counter has a non-numeric value: ');
}
}, function(error, committed, snapshot) {
if (error) {
console.log('Transaction failed abnormally!', error);
} else if (!committed) {
console.log('We aborted the transaction.');
} else {
console.log('Success!');
}
console.log("Credit data: ", snapshot.val());
});
答案 1 :(得分:1)
最后,我考虑到@chris的回答,找到了解决该问题的方法。
我使用了通过'kew'库实现的javascript promise。
这是工作代码:
var qTrans = Q.defer();
var ref = admin.database().ref('licenseCredits/' + name + '/credits');
var credits = 0;
ref.transaction( (value) => {
if (value === null) {
// the counter doesn't exist yet, start at one
return 1;
} else if (typeof value === 'number') {
// increment - the normal case
return value + 1;
} else {
// we can't increment non-numeric values
console.log('The counter has a non-numeric value: ' + JSON.stringify(value));
// letting the callback return undefined cancels the transaction
}
}, (error, committed, snapshot) => {
if (error) {
console.log('Transaction failed abnormally!', error);
qTrans.reject(error);
} else if (!committed) {
console.log('We aborted the transaction.');
qTrans.reject(error);
} else {
console.log('Success!');
console.log("Credit data: ", snapshot.val());
qTrans.resolve(snapshot.val());
}
});
return qTrans.promise;