How to run database queries synchronously in javascript [duplicate] - javascript

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.

Related

Why does await is not working in my function? [duplicate]

This question already has answers here:
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Closed 2 years ago.
I am trying to push in an array all the ids of objects that match my condition.
I am using a recursive function and I want to return a value when my recursive function has finished.
Here is my code :
const getFamilies = async function (family, famillesReliees) {
await strapi.query('famille-de-materiel').findOne({ id: family })
.then(res => {
if (res.cats_enfant.length > 0) {
res.cats_enfant.forEach(async enfant => {
famillesReliees = await getFamilies(enfant.id, famillesReliees)
})
} else {
famillesReliees.push(res.id)
}
})
return famillesReliees
}
async search() {
let value = await getFamilies(2, [])
return value
}
I don't understand why the "value" return before the end of the recursive function
This isn't doing what you think:
getFamilies(2).then(console.log('getFamilies then'))
This executes console.log immediately and passes its result (which is undefined) as the function to be executed after the getFamilies operation.
Wrap the console.log operation in a function to be executed later:
getFamilies(2).then(() => console.log('getFamilies then'))
Structurally, this is just like your use of .then() in the getFamilies function above. The only differences are:
There are no parameters/arguments for the function, so just use () instead of a variable name. (Your callback function above has a parameter called res.)
There's only one line in the function, so the curly braces {} aren't needed. (Technically this also returns the result of that line, but in this case the returned result is undefined and nothing uses it so no harm done.)

Variable changed inside arrow function not changed when consoled outside the arrow 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 2 years ago.
I am working with angular and typescript and want to change the value of the variable inside the function. I am using a service to get the data. The code is shown below:
isValue:boolean = false;
onChangeValue(list: List) {
this.someServive.getData(list).subscribe(
item => {
if(item.value === 1) {
this.isValue = true;
}
});
console.log(this.isValue); //the value is still false here
}
Good day!
It happens due to the fact, that your service call is an async operation. And browser doesn't wait when your service emits some value, which you handle in subscription block.
isValue = false;
onChangeValue(list: List) {
this.someServive.getData(list).subscribe(item => {
if (item.value === 1) {
this.isValue = true;
this.executeOnUpdateCallback();
}
});
}
executeOnUpdateCallback() {
console.log(this.isValue); // true
}
Something like this you should do to handle it. I hope, you got it (please google about js event loop)
Since javascript is asynchronous, the value won't change until the getData service call actually happens.
In your case console executes before the getData happens.
You can either try it with promise or callback
Try below:
isValue:boolean = false;
onChangeValue(list: List) {
onDataRecieved((res)=>{
console.log(this.isValue);
});
}
onDataRecieved(cb){
this.someServive.getData(list).subscribe(
item => {
if(item.value === 1) {
this.isValue = true;
cb(true);
}
});
}

access variable after define it inside a function [duplicate]

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.

how to make sure all promises are resolved in javascript? [duplicate]

This question already has answers here:
Wait for all promises to resolve
(5 answers)
Closed 8 years ago.
Suppose I have 2 or more async calls:
$scope.obja = {};
$scope.objb = {};
ref1.on('value', function (value) {
$scope.obja= value.val();
});
ref2.on('value', function (value) {
$scope.objb= value.val();
});
Later within the script I want to make sure that both of the $scope variables are set before I use them.
This example code follows the firebase examples in angularjs.
Any ideas?
Surely you can just check with an if statement?
if (($scope.obja != {}) && ($scope.objb != {})) {
// they have been set
}
Or, if they stand a chance of getting set to an empty object, just have a second variable that gets set with them:
var setn = 0;
// ...
ref1.on('value', function (value) {
$scope.obja= value.val();
setn++;
});
ref2.on('value', function (value) {
$scope.objb= value.val();
setn++;
});
// ...
// later in code, check if they have both been set
if (setn == 2) {
// they have both been set
}

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