Copy link to clipboard
Copied
I'm trying to save the documents measurement units in a variable in the main.js file for later use in the script. I am grabbing that information by passing an object in the callback function of a csinterface.evalscript('doc_info()', callback).
This is in the main.js file.
var doc_info = {}; // NEED TO SAVE THE OBJECT FROM THE JSX file for later use.
function get_doc_info() {
csInterface.evalScript('doc_info()', function(result) {
var o = JSON.parse(result);
doc_info = {
h_units: o.h_units,
v_units: o.v_units,
};
alert(doc_info.h_units); // THIS WORKS
});
}
alert(doc_info.h_units); //THIS DOES NOT WORK. I GET "UNDEFINED".
This is in the indesign.jsx file.
function doc_info() {
var obj = {
h_units: app.activeDocument.viewPreferences.verticalMeasurementUnits.toString(),
v_units: app.activeDocument.viewPreferences.horizontalMeasurementUnits.toString()
}
return JSON.stringify(obj);
}
The issue I am having is that I can console.log/alert the results from inside the callback function. But when I try to save the results to the var doc_info and then try to access doc_info outside the callback function I get "undefined".
I read somewhere on this forum or David Barrancas website that it might be because of the asynchronous nature of csinterface.evalscript(). Is that the reason? What is the solution for this problem?
Thanks
You are correct. evalScript is asynch, so you either need to restructure your code to take that into account (deep nesting a la Node), or use Promises (Promise - JavaScript | MDN)
That's just the way it is, and if you are only used to the synchronous way jsx works, it's going to be a bit of a learning curve for you, but at the end of the day it's totally worth it.
Copy link to clipboard
Copied
You are correct. evalScript is asynch, so you either need to restructure your code to take that into account (deep nesting a la Node), or use Promises (Promise - JavaScript | MDN)
That's just the way it is, and if you are only used to the synchronous way jsx works, it's going to be a bit of a learning curve for you, but at the end of the day it's totally worth it.
Copy link to clipboard
Copied
Seconded, the above is the correct answer, you can mark it as such.
Copy link to clipboard
Copied
Got it. Thank you.