Odoo javascript change value - javascript

I Use odoo 10 and want to change pivot_view.js
I'm really confused with this code. I can't change the value.
Can you explain me about the right code ?
This is my code :
var value = false;
new Model('lhp.master').call('getValues', ['date', 'idx']).then(
function (result) { value = result[0]; }
);
console.log('value =',value);
Thank you for your help.

I think the problem is with how javascript promises work!
The order of the execution of the code is a s follows:
var value = flase;
calling the server method getValue by sending an http request;
console.log('value =',value); // which will print "value =fasle" on the console
after the http request earlier in step 2 is finished and a response is retrieved from the server. The callback function will be called with the result:
function (result) { value = result[0]; }
So, make sure to write the console.log part inside the callback method, like this:
function (result) {
value = result[0];
console.log('value =', value);
}

Related

Get undefined when returning a value from an array - Node JS

I'm new to NodeJS and I get some difficulties with its asynchronous nature.
I'm requesting some data using a async function. My second function is used to retrieve an ID while knowing the name (both info are stored in the data returned by the first function).
Everytime I get the 'Found it' in the console, but the return is executed before the loop is over and I get an 'undefined'.
Should I use a callback or use async & await ? Even after lot of research about async & await and callbacks I can't figure a way to make it work !
async function getCustomers() {
try {
var customers = await axios({
//Query parameters
});
return customers;
}
catch (error) {
console.log(error);
}
}
function getCustomerId(customerName){
var customerId = null;
getCustomers().then(function(response){
for (const i of response.data){
console.log(i['name']);
if(i['name'] == customerName){
console.log('Found it !'); //This got displayed in the console
customerId = i['id'];
return customerId; //This never return the desired value
}
}
});
}
console.log(getCustomerId('abcd'));
Thanks for any help provided !
You're printing the output of getCustomerId, but it doesn't return anything.
Try returning the Promise with:
return getCustomers().then(function(response) {...});
And then, instead of:
console.log(getCustomerId('abcd'));
You should try:
getCustomerId('abcd').then(function(id) {console.log(id);})
So that you are sure that the Promise is resolved before trying to display its output

AJAX get and callbacks

I'm trying to make a variable depend on the callback from an AJAX get function, however; I can't seem to get it working. I want to make sure that defaults.context always has a value before proceeding any other code.
What am I doing wrong or how can I achieve this in a proper way?
var defaults = {
currentCase: undefined,
context: {}
}
// Set defaults
function initDefaults(){
defaults.currentCase = getCurrentCase();
defaults.context = getContext(defaults.currentCase, function(object){
console.log(object); // logs the right data
return object;
});
console.log(defaults.context); // logs undefined
}
initDefaults();
// Get the ID of the current case
function getCurrentCase(){
return global_vars.project_ID;
}
function getContext(id, callback){
var obj = {};
$.get(global_vars.template_url + "/includes/load-project-context.php?id=" + id, function(data) {
obj = JSON.parse(data);
}).complete(function() {
callback(obj);
});
}
Thanks in regards,
Enzio
You can use something like
global_vars.template_url + "/includes/load-project-context.php?id=" + id, function(data) {
obj = JSON.parse(data);
}).complete(function() {
callback(obj);
}).fail(function() {
callback(error);
});
This is callback chaining. You can use other callbacks to handle other use cases.
Please check How to know when all ajax calls are complete
You will find there all what you need with quite good explanation
May be you should continue the further code in ajax callback.
// Set defaults
function initDefaults() {
defaults.currentCase = getCurrentCase();
getContext(defaults.currentCase, function(object) {
defaults.context = object; // Continue your code inside here
console.log(defaults.context); // Logs the right data
return object;
});
// This will still return `undefined` because this line will be executed
// before the ajax request finishes.
console.log(defaults.context);
}

Returning data from Parse promise chain

I think I have got my head around Parse promise chains, but what I don't understand is how I return my data from the functions (i) back up the promise chain and (ii) back to the calling method of my original JS code.
Using the code below, the first Parse query is called, then a() and finally b() which is all fine. The console.log at each stage are for test purposes and show that the chains have been executed and in order.
I now have 3 questions:
How do I get the data back from function a() and function b() so I can access it in the main function getUserCompetitionTokens()?
How do I return any data from getUserCompetitionTokens() to the main program which has called this Parse code?
What if I want the data from function a() and also from function b() to BOTH be returned to my main program?
function getUserCompetitionTokens(comp_id) {
Parse.initialize("****","****");
currentUser = Parse.User.current();
user_competition = Parse.Object.extend("UserCompetition");
var user_comp_query = new Parse.Query(user_competition);
user_comp_query.equalTo("UserParent", currentUser);
user_comp_query.find().then(a).then(b);
function a(user_comp_results) {
var no_results = user_comp_results.length;
var id = user_comp_results[0].id;
console.log("User Competition Output: " + no_results + " results found, first item id: " + id);
var Competition = Parse.Object.extend("Competition");
var query = new Parse.Query(Competition);
return query.get(comp_id, {
success: function(competition) {
console.log("COMP - " + competition.id);
},
error: function(competition, error) {
console.log(error);
}
});
}
function b(competition) {
var Competition = Parse.Object.extend("Competition");
var query = new Parse.Query(Competition);
query.get(comp_id, {
success: function(competition) {
console.log("COMP 2 - " + competition.id);
},
error: function(competition, error) {console.log(error);}
});
}
}
You don't return :)
I'm sorry, that is just a joke on a technicality: you see, Promises are a way to express asynchronous behaviour. So you can't, strictly saying, grab the return value of a function.
However, you are already grabbing the results of each step correctly... You just didn't realize you can use it yourself.
The answer is to use your own then handler.
user_comp_query.find().then(a).then(b).then(function(results){
console.log(results); // Hooray!
});
However, keep in mind that a Promise might fail. That's why it's important to pass a second handler, which will be called whenever there is an error.
var handleSuccess = function (results) {};
var handleFailure = function (error) {};
var parsePromise = user_comp_query.find().then(a).then(b);
parsePromise.then(handleSuccess, handleFailure);

AngularJS service to variable

Is there a way to store data to a variable?
I tried:
$scope.another =
function(){
var new_data;
userService.getInfo().success(function(data){
new_data = data;
});
return new_data;
};
var data = $scope.another();
but it returns 'undefined' in the console log. Thank you
EDIT
I now get an empty array for new_data .
var new_data = [];
$scope.another =
function(callback){
userService.getInfo().success(function(data){
paymentService.getCashierParams({ "cardNumber": data.cardNumber}).success(function(data){
gameService.getAllgames({ "PID":data.GetCashierParameters.PID, "limit": 6, "skinID": 1}).success(function(data) {
callback(data.data.GetFlashGamesResult.Data.FlashGame);
});
});
});
};
$scope.another(function(result){
new_data = result;
});
console.log(new_data);
You need to think about this problem differently. Your getInfo method returns a promise. A promise's success callback is never immediately called. It may be called sometime in the future, but in the meantime your code will continue executing and the return value of $scope.another will be undefined.
Instead, place whatever logic you wish to execute within the success callback.
userService.getInfo().success(function (data) {
// Do stuff with data.
});
If you are not used to working with asynchronous data, this may seem weird. But it is much better than the alternative, which is hanging the page for potentially many seconds while a network request, database read, etc, completes.
If you are worried about indentation, you can create separate function(s) to handle the data.
function processData(data) {
// Process stuff...
return data;
}
function handleData(data) {
data = processData(data);
console.log(data);
}
userService.getInfo().success(handleData);
This is due to the asynchronous function that you called. Try to use callback instead. Something like this:
$scope.another =
function(fn){
userService.getInfo().success(function(data){
fn(data);
});
};
var data = $scope.another(function(doSomething) {
alert(doSomething);
return doSomething;
};

JavaScript set value for variable failed

I'm new to javascript. I'm trying to set value to variable with the following code but failed. Someone please help point out what is wrong with my code.
When I try to print out the value of variable "deviceLatitude", it give me "undefined". But if I print the value from inside the function, it give me the correct value. What have I done wrong?
The reason I need to have global variable for this value is because I need to use it in later stage such as compare distance with different location as needed.
var deviceLatitude;
var deviceLongitude;
function suc (p) {
deviceLatitude = p.coords.latitude;
deviceLongitude = p.coords.longitude;
// alert(deviceLatitude);
}
intel.xdk.geolocation.getCurrentPosition(suc);
alert(deviceLatitude);
suc is being called back asynchronously, so when you issue the alert after the call to intel.xdk...., suc hasn't been called yet.
Note the documentation, my emphasis:
Use this command to get the current location. This command
asynchronously acquires the approximate latitude and longitude of the
device. When data is available, the success function is called. If
there is an error getting position data, the error function is called.
Therefore, if you want to do something with deviceLatitude, you'll have to do it inside the callback.
If you're a promises type of guy, you could do:
function getCurrentPosition() {
return new Promise(function(resolve, reject) {
intel.xdk.geolocation.getCurrentPosition(resolve, reject);
});
}
getCurrentPosition.then(
function(p) {
//do something with p.coords.latitude
},
function() {
//something went wrong
}
);
Try to make anonymous function for success and other for error.
Then create another function which will be called by async when data is available.
function overrideLocalStore(lat, log)
{
alert("lat"+lat+" long"+long);
localStorage.setItem("deviceLatitude", lat);
localStorage.setItem("deviceLongitude", log);
}
intel.xdk.geolocation.getCurrentPosition(
function(p)
{
alert("geolocation success");
if (p.coords.latitude != undefined)
overrideLocalStore(p.coords.latitude, p.coords.longitude);
},
function()
{
alert("geolocation failed");
getLocation();
}
);
// Use whatever you need
alert(localStorage.getItem("deviceLatitude"));
alert(localStorage.getItem("deviceLongitude"));
As pointed out by #torazaburo, it's not possible to get data of asynchronously function out into global variable.
But to achieve what is needed, a workaround can handle that. Since this is HTML5 app, one can use localStorage to save the value and access it anytime later from other screen/function.
A simple example code will be as below:
intel.xdk.geolocation.getCurrentPosition(
function(p) {
if (p.coords.latitude != undefined) {
localStorage.deviceLatitude = p.coords.latitude;
localStorage.deviceLongitude = p.coords.longitude;
}
},
function() {
alert("geolocation failed");
}
);

Categories