access variable after define it inside a function [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm trying to access a variable outside a function, but I'm getting undefined
meliObject.get('users/me', function (err, res) {
nickname = res.nickname;
});
console.log(nickname);
How can I access nickname?
EDIT
I changed my code for:
var nickname;
meliObject.get('users/me', function (err, res) {
nickname = res.nickname;
});
console.log(nickname);
But I'm still getting undefined

The result of that function is asynchronous, so you cannot do this. Javascript flow goes like this: run meliObject.get, return immediately, run console.log(nickname), and then wait for the callback to be called. To console.log properly, just do this:
meliObject.get('users/me', function (err, res) {
nickname = res.nickname;
console.log(nickname);
});
Now, to answer your question, to declare a variable outside a function, just use var/let/const:
var a = 2;
(function () {
a = 3;
})();
console.log(a);
It will print as expected.

Related

How can I update the global variable from inside a function [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 1 year ago.
I have the following code
binance.prices('BNBBTC', (error, ticker) => {
priceNow = ticker.BNBBTC;
console.log(priceNow)
});
But I need to use the variable "priceNow" outside of that function, I have tried many things, for example:
var priceNow = ""
binance.prices('BNBBTC', (error, ticker) => {
priceNow = ticker.BNBBTC;
// console.log(priceNow)
});
console.log(priceNow) //But this just say nothing
But this doesn't work, I can't update the global variable from the function, why does this happen? and because if it works in example like this:
var a = 10;
myFunction();
function myFunction(){
a = 20;
}
console.log("Value of 'a' outside the function " + a); //outputs 20

How to run database queries synchronously in javascript [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)
Closed 4 years ago.
let positionSettings = require('setting');
function getSetting(element) {
let setting;
positionSettings.find({element: element}, function (err,docs) {
console.log(docs[0].current); // output the value
setting = docs[0].current;
});
return setting;
}
$(document).on("click", "#save" , function(e) {
console.log(getSetting("abc")); // Output undefined
});
Why is the getSetting() function returning undefined. How can I achieve it.
Because it's an async function, you can't mix async and sync functions this way, try something like this:
let positionSettings = require('setting');
function getSetting(element, callback) {
positionSettings.find({element: element}, (err,docs) => {
let setting;
console.log(docs[0].current); // output the value
setting = docs[0].current;
callback(setting);
});
}
$(document).on("click", "#save" , (e) => {
getSetting("abc", (setting) => {
console.log(setting);
});
});
The fact is that you can't be sure that the data will be avaible after the function call, the only place that you have this sure is inside the callback.
And just a hint, use arrow functions to declare anonymous functions.

beginner asynchronous value passing and returning in javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Here is the test for the function I am trying to write.
var chai = require('chai');
var doLater = require('../05-callback');
var expect = chai.expect;
describe('05-callback', function () {
it('Can get secret number', function (done) {
doLater(function (secret) {
expect(secret).to.equal(1337);
done();
});
});
});
I have written code that log's a message to the console asynchronously however, this code does not return the 1337 value asynchronously.
function doLater(secret) {
var code = 1337;
(function setImmediate(code) {
console.log("I will be executed immediately");
return code;
})(code);
setTimeout(function secret(code) {
console.log("I will be executed in 2 seconds.");
return code;
}, 2000);
}
Please let me know if this post is not clear and I will edit it. Forgive me if this post is redundant, the simular post's I found were to advanced for me. Thank you for your help!
In order to do what you want to do, you need to use a callback. Example:
function doLater(callback) {
setTimeout(function(){
//after 2 seconds call the callback
return callback(1337);
}, 2000)
}
//pass as param a function that will be called
doLater(function(result) {
console.log(result) //1337
})

MongoDB .findOne scope [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)
Closed 6 years ago.
I have a problem with var scope.
var max;
ClassModel.findOne({ class: '1a' }, function (err, class1a) {
if (err) return handleError(err);
max = class1a.members;
console.log(max);
});
console.log(max);
Why first log logs proper value, but second logs undefined?
Second console.log shows undefined because findOne of mongoose is asynchronous. When you show the first console.log, the result has been processed, in the second not.
Mongoose async operations, like .save() and queries, return
Promises/A+ conformant promises. This means that you can do things
like MyModel.findOne({}).then() and yield MyModel.findOne({}).exec()
(if you're using co).
One thing as you can do is to check when it is done, something like..
var max;
var query = ClassModel.findOne({ class: '1a' }, function (err, class1a) {
if (err) return handleError(err);
return class1a.members;
});
query.then(function(data) {
console.log(data); // will show class1a.members value
});
Docs

javascript: function returns value undefined when assigned to variable [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)
Closed 8 years ago.
I'm trying to assign a function's return value to a variable, using this stackOverflow article as a template. Here's my code:
var host = getHostName(djId, function(name) {
return name;
});
console.log(host); // undefined :(
function getHostName(id, cb) {
var reply;
userColl.findById(id, function (err, dj) {
if (err) {
reply = "db error";
} else {
reply = dj.firstName + ' ' + dj.lastName;
}
console.log(reply + ' reply'); // working as expected!
cb(reply);
});
}
the console.log(reply) is working as expected but host is still undefined when i try t call the function. what gives?
Because it's the result of getHostName which itself doesn't return anything. It seems like an asynchronous function, so if you need to do something with the value, you have to put it inside of the callback.
The inner function (callback) is executed asynchronously so when it runs, the execution of getHostName is already finished. And that's why the inner function can't return anything to the variable. All code, which will do something with the name, has to be inside of the callback.
var host = getHostName(djId, function(name) {
console.log(name); // Here you go
anotherFn(name); // Here you can have the rest of your code which needs the name
});

Categories

Resources