I'm pretty new to the world of promises, axios and the node-mssql world. So I'm probably doing this wrong.
I have a vue.js application where I'm trying to insert a record into the table. I was hoping to use promises to get the value of the identity value of the insert I just performed.
The insert part is working, but getting it back and using it, is not.
Here is my calling code which is wrapped in a Try/Catch (error below):
var addFamilyMemberRowObj;
axios
.get("http://localhost:5000/addMember?familyId="+ vm.familyId+"&memberName="+vm.memberName+"&isAdmin="+vm.isParent)
.then(response => (vm.returnId = response.data))
.then(console.log(vm.returnId["Data"][0].id))
.then(vm.memberId = vm.returnId["Data"][0].id)
.then(
addFamilyMemberRowObj = {
arrIndex: vm.addFamilyRowIndex,
familyId: vm.familyId,
familyName: vm.familyName,
familyMemberName: vm.memberName,
memberId: vm.memberId,
isParent: vm.isParent
}
)
.then(vm.addFamilyRowArray.push(addFamilyMemberRowObj))
.then(vm.addFamilyRowIndex = vm.addFamilyRowIndex + 1);
Some items you may need to know. returnId is an array. I'll show you my DB code below. the vm.returnId["Data"][0].id is the only way that I can see to get the value.
I have printed this value out, outside of the promise and it does eventually return a value. Which leads me to believe it might be a timing issue.
My database code is as follows:
app.get('/addMember', function(req,res){
var data = {
"Data":""
};
try
{
const pool7 = new sql2.ConnectionPool(config, err => {
pool7.request()
.query("INSERT INTO Member (FamilyId, MemberName, isAdmin)VALUES("+ req.query.familyId +",'" + req.query.memberName + "', '" + req.query.isAdmin + "') SELECT SCOPE_IDENTITY() as id", (err, result) => {
data["Data"] = result.recordset;
console.log(data);
res.json(data);
})
})
} catch (err) {
console.log("hasLogin: " + err)
}
});
After this is called, I have verified that the insert is working (and the console.log is also printing out the correct value [from this code]):
{ Data: [ { id: 24 } ] }
When I look at the console.log from the vue code I get the following message:
"Unable to get property '0' of undefined or null reference"
However, as I mentioned if I print out vm.returnId["Data"][0].id outside of the promise I eventually get a value on the subsequent calls (the id is 1 behind).
I know that the syntax is correct as far as getting the value, but inside the promise it doesn't like it.
I know that this is a lot to unpack. I'm probably doing many things wrong. As you can tell, a lot of these code snippets are straight from the samples. Any help would be welcome.