This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I am trying to get a shared key based on whether it already exists in the db or not. I am using Firebase store database.
The problem is that even though i assign passkey some value inside the sub-function, when I do console.log outside the function, it just prints the original passkey which was set at declaration.
I have tried using window.passkey and window.global.passkey by declaring passkey as global variable, outside all functions, but it didn't work.
I am working with a node.js project. My code is as follows:
// var passkey = {"shared_key":""} // Declaring passkey as global variable but didn't work.
const onSubmit = (formData) => {
const email_id = getUserDetails().email;
const from_db = db.collection(email_id);
const to_db = db.collection(formData.to);
var passkey = {"shared_key": ""};
// Check if there exists a shared key between `from` and `to`
// Checking for shared key in either of the db is enough.
to_db.doc(email_id).get().then((res) => {
// assume that res.exists is true.
if (res.exists) {
passkey.shared_key = res.data().shared_key; // passkey is set here
} else {
// Generate and use a shared key
...some code to generate a shared key ...
passkey.shared_key = generated_key;
}
});
console.log(passkey);
// above prints {"shared_key": ""} instead of printing the value of shared key taken from the database.
// or the one that is generated!
};
I know it is related to variable hoisting in javascript but I think there has to be some workaround.
Any help/comment is appreciated. Thanks in advance.
When you code with this pattern
function doIt () {
var something = ''
invokeFunction()
.then (function handleResult (result) {
console.log('2', something)
something = result
} )
console.log('1', something)
}
your console.log('1', something) runs before the inner function (I named it handleResult for clarity) is ever called. That's because invokeFunction() is asynchronous; it returns a Promise object.
You could rewrite this as follows:
async function doIt () {
var something = await invokeFunction()
console.log('1', something)
}
to get the kind of result you want.
With respect, you will have a very hard time coding Javascript unless you take the time to learn about async / await and Promises. In that respect the Javascript language is very different from other languages. Drop everything and learn that stuff now. Seriously.
Related
This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
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 3 years ago.
I have 2 variables. One is assigned inside a .then and the other assigned in a function. Later on only 1 is defined.
Code excerpt...
let user;
let station;
const app = express();
app.post("/api/user", (req, res) => {
user = req.body.user; // Breakpoint added here to confirm user set
}
// Uses serialport module. Called when data received on serial port
function serialPortListener(data) {
getStation(data) // Retrieves record from database
.then(s => {
station = s; // Breakpoint added here to confirm station set
...
}
I set breakpoints on both methods to confirm the variables are set. When I try to access them, later on, only user is defined. I'm assuming it's something to do with the context in which station is set?
station is not assigned anywhere else.
I believe the problem is due to the way var and let works. Try changing let with var, it should work. For the differences between var and let read this.
Edit: Ran the code here is a working code.
let user;
let station = 'ABC';
let getStation = new Promise(function (resolve, reject) {
setTimeout(() => resolve('XYZ'), 1000);
});
// Uses serialport module. Called when data received on serial port
function serialPortListener(data) {
getStation
.then((s) => {
console.log(station); // station is available with value ABC
station = s;
console.log(station); // station has value changed to XYZ
});
}
console.log(serialPortListener('data'));
The problem in your codes is in the line
getStation(data)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How can I save information locally in my chrome extension?
(2 answers)
Closed 5 years ago.
I have a string which I need in multiple functions. Therefore I want to save it in a variable. But when I try to assign it inside a function it doesn't update the variable.
var auth_code = "na";
function safeAuthCode(authcode){
auth_code = authcode;
console.log(auth_code);
}
"auth_code" prints just fine in the console at that point, but when I try to use it later it just contains "na". Not sure what I'm doing wrong tbh :/
Edit:
This is the function in which safeAuthCode is called:
function auth(){
chrome.identity.launchWebAuthFlow({
"url": "https://accounts.spotify.com/authorize?client_id="+client_id+
"&redirect_uri="+ encodeURIComponent(redirectUri) +
"&response_type=code"+
"&scope=" + encodeURIComponent(scopes),
"interactive": true
},
function(redirect_url) {
var url = new URL(redirect_url);
var code = url.searchParams.get("code");
safeAuthCode(code);
});
}
I am assuming that the problem you are having is because of the global variable that either gets overwritten in a different part of the code, or because your code at a certain point in time reloads, and the initial value gets reset.
To save such authentication code, you could make use of the sessionStorage object of your browser.
To make sure you only have 1 such object, you could use the const keyword to define your variables (in case another definition of that variable would come at a later time, you should get an error thrown)
const authorisationSettings = {
get code() {
return sessionStorage.getItem('authorisationCode') || 'na';
},
set code(value) {
return sessionStorage.setItem('authorisationCode');
}
};
function saveAuthorisationCode( code ) {
authorisationSettings.code = code;
}
saveAuthorisationCode( 'test' );
console.log( authorisationSettings.code );
This snippet doesn't work on stackoverflow, so you can find the jsfiddle here
It happens because of when your function is executed, in lexical environment of that function is already exist authcode variable and you are trying to set this one instead of global authcode
You need to change name of global variable or param of the fuction...
I have created a local class in a JavaScript file with following content:
class CustomChromeStorage {
//#region userName
get userName() {
let isCurrentValueSet = false;
chrome.storage.sync.get('userName', function (obj) {
this._userName = obj;
isCurrentValueSet = true;
});
while (true) {
if (isCurrentValueSet) {
return this._userName;
}
}
}
set userName(newValue) {
this._userName = newValue;
chrome.storage.sync.set({ 'userName': newValue }, function () {
});
}
remove_userName() {
this._userName = null;
chrome.storage.sync.remove('userName', function () {
});
}
//#endregion userName
My Idea to do such type of code is when I write somewhere else in my code like:
alert(new CustomChromeStorage().userName);
Then my code simply fetches username from chrome storage and show it via an alert. In order to fetch a value from chrome storage we need to provide a callback with as parameter the value. I know this is good practice for asynchronous process but it sometimes becomes cumbersome for me to handle all the callbacks.
I want that when I fetch value from chrome storage via my custom class to execute current code asyncronously. This is why I have written infinite while loop inside getter method of that property but the problem is when I try to alert username via custom chrome storage class my total program execution becomes hang.
The reason behind it is that I initially set isCurrentValueSet = false which never gets true inside while loop.
If anybody have any idea why it does not set to true inside while loop then please let me know.
The obj returned from sync.get is {userName: value} - use obj.userName.
The reason isCurrentValueSet doesn't get set to true is because the function is asynchronous - when the callback executes, it doesn't have access to the class variable isCurrentValueSet.
What you're trying to achieve is just wrong. It's a fact that storage requests are asynchronous for the good of the user and browser performance. You have to learn to design around it and it's easy enough when you get used to it.
You can retrieve multiple variables in one hit so if you have a section of code that needs several variables, just do:
chrome.storage.sync.get({a:"",b:"",c:0,d:[]}, function(result) {
a = result.a
b = result.b
c = result.c
d = result.d
your code
});
By passing an object in, you can request multiple variables and define defaults for if they don't yet exist in storage. Of course you don't have to extract the variables.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I have been stuck for far too long on the following problem that I really need to consider my theoretical knowledge about variable scope and callback functions in Javascript. Rather than a quick fix for my particular problem a generalized answer that tries to explain the theory behind my problem is preferred. Here is the code (that doesn't work) (oh and it uses jQuery's $.getJSON).
function getStreamerStatus(streamer) {
var channelurl = "https://api.twitch.tv/kraken/channels/";
var streamurl = "https://api.twitch.tv/kraken/streams/";
var temporary = {
status: "",
game: "",
picture: "",
name: streamer,
link: "https://www.twitch.tv/" + streamer
};
$.getJSON(streamurl + streamer, createCallback(temporary));
$.getJSON(channelurl + streamer, createCallback(temporary));
return temporary;
}
After some searching I used the "createCallback()" function in an attempt to make the "temporary" object visible to the callback function.
function createCallback(tmpobj) {
return function(json) {
//get's some information and stores it in the object passed as tmpobj
filterOut(json, tmpobj);
};
}
And in the end in the main function I have an array with names of twitch streamers and for each name the "getStreamerStatus()" function is called and the returned object is stored in an array.
function TwitchInit() {
var channels = [/*filled with strings of streamer names*/];
var response = []; //array with objects with all the information
for(var i = 0; i < channels.length; i++) {
response.push(getStreamerStatus(channels[i]));
}
parseContent(response); //not relevant for now
//for debugging
for(var j = 0; j < response.length; j++) {
console.log("--responseArray with Objects--");
for(var prop in response[j]) {
if(response[j].hasOwnProperty(prop)) {
console.log(prop + ": " + response[j][prop]);
}
}
}
}
The problem here is that if I log the objects to the console only the "link" and "name" properties of the objects have some content and the other properties who're supposed to be written by the "filterOut()" function always remain empty. According to the console the communication with the Twitch server is fine and I can read the response header/object from the console so that rules out. And since the "name" and "link" properties are also different at each log to the console that means that each time a new object is created which is fine. That leads me to the conclusion that the "temporary" object still somehow isn't visible to the callback function inside $.getJSON despite my attempt with "createCallback()" to make the object visible to the "filterOut()" function. I have found a lot of information about variable scope in JavaScript but so far it hasn't helped my to solve my problem. I have no clue what I am doing wrong here and I'm starting to get frustrated. I really hope someone can enlighten me here.
I think there is no problem is closure here, the only problem is that your getStreamerStatus function will perform async tasks but will return a value directly, and use it without waiting the async calls (getJSON) to complete.
Try to put you debug logs inside a setTimeout with few seconds delay ;)
To so things better you should rewrite your getStreamerStatus to only returns the data after the getJSON calls are done, not before, with a callback as parameter, or by returning a promise.
Or you should have something (ie: an event) to tell your function that the calls are finished, and that it can process the results.
I am developing an AngularJS application and found the following behavior.
I have two functions in my service. The first function returns all the categories stored in the database and the second returns one category by its id.
Here is my service:
angular.module('categoriesRepository', [])
.service('categoriesRepository', ['$cordovaSQLite', 'sqliteHelper',
function ($cordovaSQLite, sqliteHelper) {
//this works - returns an array with all categories
this.getAll = function () {
var categories = [];
$cordovaSQLite.execute(sqliteHelper.getDb(),
"SELECT * FROM categories;")
.then(function (res) {
for (var i = 0; i < res.rows.length; i++) {
categories.push(res.rows[i]);
}
});
return categories;
}
//this works not - returns undefined
this.getById = function (id) {
var category;
$cordovaSQLite.execute(sqliteHelper.getDb(),
"SELECT * FROM categories WHERE id = ?;", [id])
.then(function (res) {
category = res.rows[0];
});
return category;
}
}]);
I know that I can use Angulars $q to run functions asynchronously, and use their values when they are done processing.
Why does the getById function return the category directly and the getAll wait until the array is filled?
EDIT
I had the getAll function posted wrong. There is no return statement before $cordovaSQLite.execute
UPDATE:-
After your question is updated.
In the first example your are creating an array first by doing var categories = [];and then returning this array before finishing your async call. When your async call completes it just pushes certain elements into the array thus not destroying the reference to the array (categories ) variable. When it is returned back if you will debug it you will find the function returning an empty array and later when the async call succeeds only then the array will be filled.
In the second example you are creating just a variable and then returning it before the async call finishes. But then the async call is finished you assign the variable to a new value. thus destroying the earlier reference.
Solution:-
Though not a preffered approach to make it work. you will have to maintain the category variable reference. for this you can use angular.copy OR angular extend
So the second part of your code should be like
this.getById = function (id) {
var category;
$cordovaSQLite.execute(sqliteHelper.getDb(),
"SELECT * FROM categories WHERE id = ?;", [id])
.then(function (res) {
angular.copy(res.rows[0], category);
//now the reference to the category variable
//will not be lost
});
return category;
}
Better Practice:-
The way you have been developing this application is wrong. Async calls should not be handled this way. I earlier asked a question just to clarify the way to handle the async calls and state inside the angular app, factories and controllers please have a look here. It provides two ways to handle the state and async calls. There might be many more practices out there but these two suit me best.
It is unfortunate that this approach appears to 'work' because it is caused by the modification of the returned array object "at some unspecified time" after it is returned.
In the usage the array is accessed/observed after1 it has been modified by the asynchronous call. This makes it appear to function correctly only because of the (accidental) asynchronous-later-than observation.
If the observation was prior to the actual completion of the SQLite operation - such as immediately after the getAll function call - it would reveal an empty array.
Both functions are incorrectly written and the first accidently releases Zalgo (or perhaps his sibling).
See How do I return the response from an asynchronous call? for more details.
1 Chrome's console.log can be confusing as it works like console.dir and thus may be showing the current value and not the value when it was invoked.
As stated already, this is a bad approach. You can't use result of your function immediately after it returns.
However I didn't see the answer to your exact question: why do they behave differently?
It happens because with an array you return a reference to an object (type Array). Later on you use same reference to modify contents of the object, i.e. push new items into the array.
However in second function you modify the reference itself. You make you local variable categories point to a new object. Thus old object (reference to which was returned to outer scope) remains untouched. To make it work the same way you should have written
category.row = res.rows[0];
You return the result of the execute in the first case, whereas you return the variable in the second case, which has most likely not been populated yet.