1

I have this array

[
   {id: "1280-00-477-5893-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514575144592", name: "Cancelled -> Replaced by 1280005462575", price: "$324", imgsrc: "https://firebasestorage.googleapis.com/v0/b/honeyb…=media&token=3acd47c0-773a-48c1-8956-9a025769b91e", availableqty: "4", …}
   {id: "1510-00-140-1627-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514546926962", name: "AIRPLANE UTILITY", price: "$890", imgsrc: "https://firebasestorage.googleapis.com/v0/b/honeyb…=media&token=01267792-8f7f-40a6-921b-699e4366e5cb", availableqty: "65", …}
]

I want to use the id of each object and run it against firebase database to retrieve more data.

  $('.checkout').click(function(){

// is user authenticated 

 firebase.auth().onAuthStateChanged((user) => {
    if (user) {
        var userId = firebase.auth().currentUser.uid;
        for (var i = 0; i < cartarry.length; i++) {
                    var id = cartarry[i].id;
                    var finalqty = cartarry[i].quantity;
                    var price = cartarry[i].price;
                    var itemref = Cataloguedatabase.ref('/Listings/' + id).once('value', function(snapshot) {
                        var listingdetail = snapshot.val();
                        // subtract ordered quantity from available quantity
                        var availableqty = parseInt(listingdetail.Ava_QTY);
                        var orderedqty =  parseInt(finalqty);
                        var qtyleft = availableqty - orderedqty;
                        console.log("orderd qty  ", orderedqty)
                        console.log("Available qty  ", availableqty)
                        console.log("What is now left is ", qtyleft)
                        console.log("priceee is ", price)                           

                    })
    }

} else {

    window.location = "../html/auth.html"
}

})

})

The code works but for some reason it only print out the last array value for price and orderedqty. for example instead of it printing out $324 and 890, it prints out 890 twice and like quantity too. What am I doing wrongly and how can I fix this?

Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
e.iluf
  • 1,389
  • 5
  • 27
  • 69
  • 1
    `let id =` ... `let finalqty =` ... etc. –  Jan 20 '18 at 18:06
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) –  Jan 20 '18 at 18:08
  • It's because `var price` is scoped to the handler, so the console only shows you the last value it set to, hence you're getting only the last one displaying. `for` will have it's own scope with `let`, though, so `let price = ...` . – Jared Farrish Jan 20 '18 at 18:16

1 Answers1

0

declare your variables using let not var

let id = cartarry[i].id;
let finalqty = cartarry[i].quantity;
let price = cartarry[i].price;
Ali Faris
  • 17,754
  • 10
  • 45
  • 70