簡體   English   中英

在 Firebase 中同步運行功能

[英]running functions synchronously in firebase

我正在嘗試調用一個函數來從“子產品”表中獲取一個值並將其插入到另一個表中。 但是,我返回的值不是從表中獲取最新值,它甚至在函數的快照部分執行之前就已返回。 我希望它同步運行。 有沒有更好的寫法。

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;
};

這是我調用上述函數的地方:

var gstans = getGSTvalues($('#edit_ProductSubType').val());

任何幫助,將不勝感激

使用同步邏輯將是一個很大的倒退。 這里最好的解決方案是正確使用異步模式,並為getGSTvalues()提供回調函數,該函數在異步操作完成並接收結果作為參數后執行。 嘗試這個:

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...
});

另一種選擇是從getGSTvalues()返回SubProductRef的承諾,並在調用范圍內對其應用then() ,盡管這會使函數在很大程度上變得多余。

另請注意,JS 區分大小寫,因此gstVargstvar 我在上面更正了這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM