Why calculation variable in JavaScript Promises does not recognise at outside [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
var appCounts = 0;
applicationsService.getApplicationCountByJob(job.id).then((appcount) => {
appCounts = appCounts + appcount;
});
company.applications = appCounts;
appCount has lost value in company.applications = appCounts;
Please let me know how to solve that issue.

your function getApplicationCountByJob is probably asynchronous, meaning
company.applications = appCounts;
gets executed before
appCounts = appCounts + appcount;
move inside another then to get it work:
var appCounts = 0;
applicationsService.getApplicationCountByJob(job.id)
.then((appcount) => {
appCounts = appCounts + appcount;
})
.then(() => {
company.applications = appCounts;
});

Related

Unable to return value inside function in node.js [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed last month.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
Unable to return value inside function in node.js . Below is my function which I am calling from another function to get desired value but I am getting undefined.
const getBBBMeetingInfo = (meetingID) => {
let bbbHttp = bbb.http;
let getMeetingInfo = api.monitoring.getMeetingInfo(meetingID);
let val;
bbbHttp(getMeetingInfo).then((result) => {
let newRes = {};
newRes = result;
newRes.meetingID = meetingID;
if(newRes.returncode == 'FAILED'){
updateNotificationCallStatus(meetingID)
}
val = newRes.returncode
});
return val
}
calling fuction like this
let bn = getBBBMeetingInfo(ele.meetingId);
console.log(bn)//undefined
I am new to node.js. Please let me know how I can get it and use it as returned value.

Array undefined from Fetch API [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I can access the array 'words' in global scope but when I try to find an item by typing 'words[index]' , it returns undefined. How can I solve this?
let words = [];
function fetchWords() {
fetch("https://www.themealdb.com/api/json/v1/1/categories.php")
.then((res) => res.json())
.then((data) => {
for (let i = 0; i < 13; i++) {
words.push(data.categories[i].strCategory);
}
});
}
fetchWords();`
console.log(words); //This works
console.log(words[2]); // But this does not. Why?
This is because you call:
console.log(words[2]);
before you fetch the result. You need to await fetchWords before console.log(words[2]);

Return a value from a setTimeout [duplicate]

This question already has answers here:
how to make Javascript setTimeout returns value in a function
(2 answers)
Javascript return value from setTimeout [duplicate]
(1 answer)
Get return value from setTimeout [duplicate]
(5 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm trying to return a value calculated in a setTimout. But it seems like I can't do get this value. I read that to do this I must use promises. Am I obliged to use this like this exemple : https://italonascimento.github.io/applying-a-timeout-to-your-promises/ ?
My code :
renderTeaserBackground = () => {
return setTimeout(function() {
this.setState({ teaserAnimCount: this.state.teaserAnimCount + 1 });
let teaserBackground = teaserBgImg[this.state.teaserAnimCount];
console.log(teaserBackground);
}.bind(this), this.state.teaserAnimDuration * 1000);
return 'teaserBackground';
}
Thanks
You can use a Promise!
ES6 way - Standard Promises:
renderTeaserBackground = () => new Promise(res => {
setTimeout(_ => {
this.setState({teaserAnimCount: this.state.teaserAnimCount + 1});
let teaserBackground = teaserBgImg[this.state.teaserAnimCount]
res(teaserBackground) //Return it here!
}, this.state.teaserAnimDuration * 1000);
})
To use this outside, you can do:
const mainLogic = _ => {
return renderTeaserBackground().then(teaserBackground => {
/* Use teaserBackground as you need! */
})
}
ES7 way - Harmony async/await
const mainLogic = async _ => {
const teaserBackground = await renderTeaserBackground()
/* Use teaserBackground as you need! */
}

Node JS Promise won't return a value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
The below code is not returning a value back but it console logs out fine. Any ideas how I can set the value of X?
var dbSize = dbo.collection('Items').count()
var x = 0
x = dbSize.then(len => {
return len
})
This is what is being logged 'Promise { }' however if I simply write this:
dbo.collection('Items').count()
var x = 0
dbSize.then(len => {
console.log(len)
})
then It logs out fine.
you can warp your code with an async function and then use await to make your code work like synchronized code
const a = async () =>{
var dbSize = await dbo.collection('Items').count()
console.log(dbSize)
}
a();

Retrieve value from nested functions javascript [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 7 years ago.
I have had a look, and see some great examples of nesting functions, but even with reading them, I cannot see why I am getting undefined when i call this function:
function readBttnDetec() {
var devid = localStorage.getItem('vBttn');
var bd = 0;
bd = ble.read(devid, 'fffffff0-00f7-4000-b000-000000000000',
'FFFFFFF2-00F7-4000-B000-000000000000',
function(t) {
var data = new Uint8Array(t)
console.log('returns: ' + data[0]); // this returns 6
return data[0];
}, function(f) {
console.log(f);
});
return bd;
}
This is the call:
//check button state
var detecs = readBttnDetec();
console.log(detecs);
if(detecs == 2) {
// fall detection disabled
$('#playfall').removeClass('km-state-active');
} else if(detecs == 6) {
// fall detection enabled
$('#playfall').addClass('km-state-active');
} else {
// error reading button
}
I am missing something simple I am sure of it, but I cannot see it.
Thanks in advance

Categories

Resources