[英]running functions synchronously in firebase
I am trying to call a function to get a value from a 'subproduct' table and insert it in to another table.我正在尝试调用一个函数来从“子产品”表中获取一个值并将其插入到另一个表中。 However the value which I am returning is not fetching the latest value from table and it is getting returned even before the snapshot part of the function is getting executed.
但是,我返回的值不是从表中获取最新值,它甚至在函数的快照部分执行之前就已返回。 I want it to run synchronously.
我希望它同步运行。 Is there a better way in which it can be written.
有没有更好的写法。
function getGSTvalues(para1) {
var gstVar = 1;
var gstVarPromise = SubProductRef.once("value").then(function(snapshot) {
snapshot.forEach(function(child) {
if (para1 == child.val().subproductName) {
gstvar = child.val().gst;
console.log("InsidePromise" + gstVar);
}
});
console.log("outside fun : " + gstVar);
});
console.log("outside fun1 : " + gstVar);
return gstVar;
};
This is where I am calling the above function:这是我调用上述函数的地方:
var gstans = getGSTvalues($('#edit_ProductSubType').val());
Any help would be appreciated任何帮助,将不胜感激
Using synchronous logic would be a big step backwards.使用同步逻辑将是一个很大的倒退。 The best solution here would be to use the asynchronous pattern correctly and provide a callback function to
getGSTvalues()
which is executed after the async operation completes and receives the result as an argument.这里最好的解决方案是正确使用异步模式,并为
getGSTvalues()
提供回调函数,该函数在异步操作完成并接收结果作为参数后执行。 Try this:尝试这个:
function getGSTvalues(para1, cb) {
var gstVar = 1;
var gstVarPromise = SubProductRef.once("value").then(function(snapshot) {
snapshot.forEach(function(child) {
if (para1 == child.val().subproductName) {
gstVar = child.val().gst;
}
});
cb && cb(gstVar);
});
};
getGSTvalues($('#edit_ProductSubType').val(), function(gst) {
console.log(gst);
// work with the value here...
});
Another alternative would be to return the promise from SubProductRef
from getGSTvalues()
and apply then()
on that in the calling scope, although this would render the function largely redundant.另一种选择是从
getGSTvalues()
返回SubProductRef
的承诺,并在调用范围内对其应用then()
,尽管这会使函数在很大程度上变得多余。
Also note that JS is case sensitive so gstVar
is not the same as gstvar
.另请注意,JS 区分大小写,因此
gstVar
与gstvar
。 I corrected this above.我在上面更正了这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.