Global Variable not changing value in function [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
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
}
);
});

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

Related

How to get a value back from a multilevel nested callback? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 17 days ago.
I am using the mssql npm library which is working, but I am struggling to get the recordset returned from the sub-level callback.
How do I get the recordset back when it's multiple layers of callback?
let storedRecordset = await doQuery();
async function doQuery(){
let recordset;
const ps = new sql.PreparedStatement(/* [pool] */)
ps.input('param', sql.Int)
ps.prepare('select #param as value', err => {
// ... error checks
ps.execute({param: 12345}, (err, result) => {
// ... error checks
recordset = result;
// release the connection after queries are executed
ps.unprepare(err => {
// ... error checks
return recordset;
})
})
})
}
Thanks
let storedRecordset = await doQuery();
function doQuery() {
return new Promise((r) => {
let recordset;
const ps = new sql.PreparedStatement(/* [pool] */);
ps.input("param", sql.Int);
ps.prepare("select #param as value", (err) => {
// ... error checks
ps.execute({ param: 12345 }, (err, result) => {
// ... error checks
recordset = result;
// release the connection after queries are executed
ps.unprepare((err) => {
// ... error checks
r(recordset);
});
});
});
});
}

Javascript async function returns 'undefine' value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 28 days ago.
I am new to Javascript. I am trying to retrieve data from a MQTT broker through an async JavaScript function, querydevice. Here I am successfully getting a response from functions.logger.log(`Query msg retrived from MQTT ${msg}`) as expected.
const querydevice = async () => {
let msg;
try {
await client.subscribe("test/result");
client.on('message', function(topic, message) {
msg = message.toString();
var tp = topic.toString();
client.end();
functions.logger.log(
`Query msg retrived from MQTT ${msg}`
);
});
return {
state: msg,
}
} catch (e) {
process.exit();
}
};
I am calling the function querydevice in another function called app.onQuery as below. But I am not getting a correct response in functions.logger.log(`Device state:${dt.state}`). It shows undefined in place of the dt.state variable in the logs.
app.onQuery(async (body) => {
const dt = await querydevice();
functions.logger.log(`Device state:${dt.state}`);
return {
requestId: body.requestId,
payload: {
devices: {
"OOB-Group-7": {
on: false,
online: true
}
}
}
}
});
Can some one guide me where I am doing wrong?
I tried removing await, used .then instead in app.onQuery function. Also I tried .toString() for the dt variable.

Why does my Array Pushes doesnt work the right way? Vue [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
a simple question: I want to add simple numbers to an array, which I want to compare later to another array. But I can't access the content of the update-Array.
This is my code:
checkForUpdates(curr_dataset) {
var current = curr_dataset;
var update = [];
//put in array
axios.get('http://localhost:3030/disruptions/', {
params: {
DisruptionCategory: 0
}
})
.then(response => {
console.log("push " + response.data.data.length)
update.push(response.data.data.length);
})
.catch((error) => {
console.log(error.data);
});
axios.get('http://localhost:3030/disruptions/', {
params: {
DisruptionCategory: 1
}
})
.then(response => {
console.log("push " + response.data.data.length)
update.push(response.data.data.length);
})
.catch((error) => {
console.log(error.data);
});
axios.get('http://localhost:3030/disruptions/', {
params: {
DisruptionCategory: 2
}
})
.then(response => {
console.log("push " + response.data.data.length)
update.push(response.data.data.length);
})
.catch((error) => {
console.log(error.data);
});
axios.get('http://localhost:3030/disruptions/', {
params: {
DisruptionCategory: 3
}
})
.then(response => {
console.log("push " + response.data.data.length)
update.push(response.data.data.length);
})
.catch((error) => {
console.log(error.data);
});
console.log(update[0]); //HERE I GET "undefined"
}
To continue and compare the content of my update-Array with the current-Array I need to be sure that I've got the right values...
Anyone an idea?
This code is asynchronous. I would recommend you take a look at how asynchronous javascript code works.
Basically what you are doing is this:
Creating an empty array
Make an Axios get request. When this completes, go to 2.1, if it fails go to 2.2.
2.1 Push to Array
2.2 log error
Make an Axios get request. When this completes, ..
3.1 ..
3.2 ..
..
Show me what the element at index 0 in the array.
You see, the calls 2.1/3.1/4.1 only get executed, WHEN the request returns successful. Javascript is not blocking the script until they complete. So until it gets to 5., non of these requests should have completed or failed. That is why nothing gets pushed to the array.
Here on SO you will find many examples, blog entries and questions already relating to that.
Furthermore, you should start using async/await for those use cases. It is just way cleaner code and is easier to debug (in my opinion). Also use const instead of var.
an example would be:
async checkForUpdates(curr_dataset) {
const current = curr_dataset
const update = []
const promises = [0,1,2,3].map(async i => {
try {
r = await axios.get('http://localhost:3030/disruptions/', {
params: {
DisruptionCategory: i
}
})
// execute the rest of the code here, like pushing to the array
} catch (e) {
console.log(e.data)
}
await Promise.all(promises)
console.log(update[0])
}

How to return new promise object from backend service file to backend controller? [duplicate]

This question already has answers here:
How do I convert an existing callback API to promises?
(24 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
I am trying to connect to Recurly API in backend service file, then return as a new promise to backend controller.
For some reason my code does't work.
I keep receiving this error message:
0|account- | TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type undefined
This is my code, the API configuration and other setup works fine. Keep in mind this is part of the project code.
Service.js:
const Recurly = require('recurly-js');
function TeamService({}) {
this.updateBillingInfo = (team_id, body) => {
const recurly = new Recurly(
{
API_KEY: config.recurly.API_KEY,
SUBDOMIAN: config.recurly.SUBDOMIAN,
ENVIRONMENT: config.recurly.ENVIRONMENT,
DEBUG: config.recurly.DEBUG,
API_VERSION: config.recurly.API_VERSION
}
);
return new Promise((resolve, reject) => {
let res;
let err;
recurly.billingInfo.update(team_id, { token_id: body.id }, function (errResponse, response) {
if (errResponse) {
err = errResponse.data.error;
}
if(response){
res = response;
}
});
resolve(res);
reject(err);
});
};
}
}
Controller.js:
function Controller({ teamService, httpStatus, }) {
this.updateBillingInfo = (req, res) => {
const {
team_id,
body
} = req;
teamService.updateBillingInfo(team_id, body).then(function(result){
console.log(result);
return httpStatus.twoHundredSuccess(res, {result});
}).catch(function(err){
console.log(err);
httpStatus.fiveHundredError(res, err);
});
}
}
I expect that the function in service works get information from API. return as a new promise to controller file. But it is not working in service.js. I am not very good with promise. Please let me know which part I did wrong.
Your resolve and reject should be inside the callback of async function:
recurly.billingInfo.update(team_id, { token_id: body.id }, function(
errResponse,
response
) {
if (errResponse) {
reject(errResponse.data.error);
}else{
resolve(response);
}
});

How to get data from axios response [duplicate]

This question already has answers here:
javascript says JSON object property is undefined although it's not
(4 answers)
Closed 3 years ago.
Trying to make a http request with axios, then accessing some property from request. Property is undefined, although it is present
public getApiURL() {
axios.get('https://xxxxxxxxx.com/metadata.json')
.then(res => {
console.log(res.data); // {"apiUrl":"https://xxxx.com/Api"}
console.log(res.data.apiUrl); // undefined
}).catch(err => {
console.log('error', err);
})
}
Try This one
`
public getApiURL=async ()=> {
try{
let result= await axios.get('https://xxxxxxxxx.com/metadata.json')
const data = JSON.parse(result.data);
console.log(data.apiUrl);
}catch(err){
console.log(err);
}
}
`

Categories

Resources