Get a value from Firebase and update it with the current value + 1

≯℡__Kan透↙ 提交于 2019-12-25 16:52:02

问题


So yeah the title has the question. A little information this is what my Firebase database looks like:

And this is the current code:

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
}

Basically, What I want is for the qty + 1 to be returned to the function updateQTY.

Maby I have to do a completely different way but that's fine, I just don't understand how to do it. I understand the fact that the function that actually gets the current qty has to return it, but then I don't understand how to catch it in the other function.


回答1:


You can't return a value which won't be available right away, so currentQTY needs to return a promise for the new quantity; then, in updateQTY, wait for that promise to fulfill and then update the data.

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

If you can use async/await:

export async function updateQTY(barcode) {
  const qty = await currentQTY(barcode);

  database.ref('items/' + barcode).update({qty}));
)

Or even

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

However, you could accomplish this more easily and robustly with transactions:

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

Or if you prefer

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

Using transactions has the advantage that it will correctly handle situations in which multiple users are trying to update the data at the same time. For more information, see the documentation.



来源:https://stackoverflow.com/questions/43442796/get-a-value-from-firebase-and-update-it-with-the-current-value-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!