【问题标题】:Get a value from Firebase and update it with the current value + 1从 Firebase 获取一个值并使用当前值 + 1 更新它
【发布时间】:2017-09-12 13:24:27
【问题描述】:

所以是的,标题有问题。一点信息,这是我的 Firebase 数据库的样子:

这是当前的代码:

export function updateQTY(barcode) {
  database.ref('items/' + barcode).update({
    qty: currentQTY(barcode)
  })
}
export function currentQTY(barcode) {
  database.ref('items/' + barcode).once('value').then(function(snapshot) {
    var qty = snapshot.val().qty
    console.log(qty)
  })
  return qty + 1
}

基本上,我想要的是将 qty + 1 返回到函数updateQTY

也许我必须采取完全不同的方式,但这很好,我只是不明白该怎么做。我理解实际获取当前数量的函数必须返回它,但是我不明白如何在另一个函数中捕获它。

【问题讨论】:

    标签: javascript firebase react-native firebase-realtime-database react-native-android


    【解决方案1】:

    您不能返回一个无法立即使用的值,因此currentQTY 需要为新数量返回一个promise;然后,在 updateQTY 中,等待该承诺履行并然后更新数据。

    export function updateQTY(barcode) {
      return currentQTY(barcode)
        .then(qty => database.ref('items/' + barcode).update({qty}));
    )
    
    export function currentQTY(barcode): Promise<number> {
      return database.ref('items/' + barcode).once('value')
        .then(snapshot => snapshot.val().qty + 1);
    }
    

    如果你可以使用 async/await:

    export async function updateQTY(barcode) {
      const qty = await currentQTY(barcode);
    
      database.ref('items/' + barcode).update({qty}));
    )
    

    甚至

    export async function updateQTY(barcode) {
      database.ref('items/' + barcode).update({qty: await currentQTY(barcode)});
    )
    

    但是,您可以通过事务更轻松、更可靠地完成此任务:

    export function updateQTY(barcode) {
      return database.ref('items/' + barcode).transaction(data => {
        data.qty++;
        return data;
      });
    }
    

    或者如果你喜欢

    export function updateQTY(barcode) {
      return database.ref(`items/{$barcode}/qty`).transaction(qty => qty++);
    }
    

    使用事务的优点是可以正确处理多个用户同时尝试更新数据的情况。如需更多信息,请参阅documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2023-01-01
      • 2016-08-05
      • 1970-01-01
      • 2019-01-24
      • 2020-05-04
      相关资源
      最近更新 更多