How to call variable from async function [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 months ago.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
This line of code is getting document count from firestore database it works fine when i call the variable inside the function but outside its undefine.
var LM35TOTALRES; // I WANT TO STORE HERE
db.collection("LM35").get().then(function(querySnapshot) {
LM35TOTALRES = querySnapshot.size //DATA THAT I WANT
console.log(LM35TOTALRES); // THIS IS WORKING
});
console.log(LM35TOTALRES); // NOT WORKING

I believe this is because the function is async so it finishes setting the value after the log outside, One solution is to return the value needed in the variable directly and await it like so const LM35TOTALRES = await (db.collection("LM35").get()).size
This occurs due event loop scheduling you can find some good examples in this video about min 2 or so

use let instead of var
let LM35TOTALRES;

Related

Getting a single value with the PerformanceEntry API [duplicate]

This question already has answers here:
console.log() async or sync?
(3 answers)
Closed 1 year ago.
When I try to get the page load time using PerformanceEntry I'm able to get an array of data but how do i get only the value of "domComplete" or "duration" instead of the whole list of data; Here's the code:
const time = performance.getEntriesByType("navigation");
console.log(time[0]);
console.log(time[0]['domComplete']);
when i console log (time[0]), this is what i get:
but when using (time[0]['domComplete']) or (time[0]['duration']), it returns 0
Try this
console.log(time[0].domComplete);

JQuery does not set variable after $.get [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
(14 answers)
Closed 3 years ago.
Hello gurus in the house. It sounds like a duplicate but I am having a tough time with it since 48hrs past. The question is based on a jQuery. I have a file that i would like to pass into a variable then later use the variable in other places of my code. The file only contains 'I love you'.
<script>
var kk;
$.get('k.txt', function(data) {
kk = data;
}, 'text');
alert(kk); //undefined
</script>
The result of the alert is undefined and it does not work in opera browser. I can alert it like this.
<script>
var kk;
$.get('k.txt', function(data) {
alert(kk); //alert is fine
}, 'text');
</script>
I don't mind if you can show me any other working process apart from this. Please I need this so badly and I have being dealing with this since yesterday. Thank you sirs for understanding.

empty array is returned even after pushing value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have declared an empty array called answerDataArray and pushed values into the array (values are snapshots from firebase DB). When I can use console.log(answerDataArray) outside the forEach loop it showing an empty array but when I do console.log(answerDataArray) anywhere inside the forEach loop I get the populated array. Please tell what happening here.
var ideationContestRef = ideationDataRef.child(contestDataRef.key);
ideationContestRef.once("value", function(snapshot){
if(snapshot.child("answers").exists()){
snapshot.child("answers").ref.once("value", function(snapAnswerKey){
var answerKey = Object.keys(snapAnswerKey.val());
var answerDataRef = db.ref("answerData");
var answerDataArray = [];
answerKey.forEach(function(key){
answerDataRef.child(key).once("value", function(snapAnswerData){
answerDataArray.push(snapAnswerData.val());
});
});
console.log(answerDataArray);
// res.render("ideation", {id: contestId, layout: 'styled.handlebars', page: 'ideation', user_logged_in: user_presence, contestData: snapshot.val(), answerDataArray: answerDataArray});
});
}
Your problem probably is the fact that answerDataRef.child(key).once("value", function(snapAnswerData){ is async, therefore you can't expect to have values line after the forEach that you have mentioned.
Maybe you can use Promise in order to return async value.

JQuery - gloabl array not working as expected [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
This gives me the content of a file, in an alert box. As long as the alert is inside the get-functions block it's working fine:
var allActivities = [];
$(document).ready(function() {
$.get('./activities.txt', function(result) {
currentActivity = result.split(",");
allActivities.push(currentActivity);
alert(allActivities); // Alert box returns correct results
});
}
But when I move the alert outside of the get-function scope, the alert box is empty. I'm guessing I have messed up with some scopes, but I can't figure out what.
var allActivities = [];
$(document).ready(function() {
$.get('./activities.txt', function(result) {
currentActivity = result.split(",");
allActivities.push(currentActivity);
});
alert(allActivities); // Alert box is empty
}
I need the array allActivities to be global so that I can access it outside of the .get function. So I need the last code example to work. In other words, the last code example needs to alert the content.
Gathered from comments:
Since $.get is asynchronous the alert is called before my array is populated. The global array is working as expected. The alert needs to be called at a later point, for instance with a button click after page load.
I have tested it and it worked.

chrome.tabs.executeScript - how to make a script return a value? [duplicate]

This question already has an answer here:
about chrome.tabs.executeScript( id,details, callback)
(1 answer)
Closed 8 years ago.
I am injecting a script into a tab using chrome.tabs.executeScript. Its last parameters is a callback function that will be called with The result of the script in every injected frame. . How do I make my script return a result? I tried adding a simple return statement at the end of my js, but nothing got returned.
As RobW corrected me, a function is not necessary, just make sure that the desired data is the last expression and of course that is JSON-serializable.
chrome.tabs.executeScript(tabId,
{code:"document.charset"},
function(results){
// results[0] will now contain the charset for the page in question
});

Categories

Resources