0

I have a nodejs app and I am trying to pass a value called membership to a page. I initialize it and try to update its value in a function but the output doesn't change. It still outputs 0. Please I need help

app.get("/",(req,res)=>{
    var membershipStrength = 0;
    memberData.findAll()
        .then(members =>{
            // console.log(members.length);
            membershipStrength = members.length;
            console.log(membershipStrength);
        })
        .catch(err => {
            console.log("Error fetching members data: ", err);
        });
    console.log(membershipStrength);
    return res.render("index",
        {
        page: "Admin",
        membershipStrength: membershipStrength,
        // tableData : global.dataOut
        }
    );
});
Mudi
  • 1
  • 1

1 Answers1

0

You're calling the render function before the call to findAll completes. Thus, when your server responds to the HTTP request, it still has the original value of membershipStrength in it.

You need to put the call to render inside the then handler:

app.get("/",(req,res)=>{
    var membershipStrength = 0;
    return memberData.findAll()
        .then(members =>{
            // console.log(members.length);
            membershipStrength = members.length;
            console.log(membershipStrength);
            return res.render("index",
            {
              page: "Admin",
              membershipStrength: membershipStrength,
              // tableData : global.dataOut
            }
            );
        })
        .catch(err => {
            console.log("Error fetching members data: ", err);
        });

});
Dancrumb
  • 26,597
  • 10
  • 74
  • 130