Reputation: 951
I'm new to Datapower Gateway script (and Javascript) and following situation totally confuses me. Look:
var inputJson = "default";
//Reading json from input and covert it to string
session.input.readAsJSON( function ( error, json) {
if ( error ) {
session.reject( 'Input is not a valid JSON document' );
return;
}
inputJson = JSON.stringify(json);
console.debug("Inside: ", inputJson);
});
console.debug("Outside ", inputJson);
In Datapower console will be following:
"Inside: { long json string }"
"Outside: default"
It totally breaks my mind and distort my knowleges about variables scopes. Is it feature of javascript, datapower script implementation or what?
UPD. And another brain-cracked thing:
function getFile(options){
var file="default";
urlopen.open(options,function(error, response){
if(error){
console.error("Unable to find file: "+JSON.stringify(error));
}else{
if(response.statusCode==200){
response.readAsBuffer(function(error, responseData){
if(error){
console.error("Unable to open file: "+JSON.stringify(error));
}else{
console.error("Before: ", file);
file=responseData.toString('ascii');
console.error("After: ", file);
}
});
}else{
console.error("Unable to open file: "+response.statusCode);
}
}
});
return file;
}
console.error("Func result: ", getFile(openSchemaOptions));
Console result:
"Func result: default" (sic!)
"Before: default"
"After: --json string--"
How it could be possible to print function result before the function execution?!
Upvotes: 1
Views: 3959
Reputation: 7059
Because the session.input.readAsJson();
will take more time to execute. if we number the sequential execution of events in this peace of code:
// 1. functions and vars are moved automatically to the top by the js interpreter in your browser. So this is first
var inputJson = "default";
// 2. a function gets called passing another function as parameter => the callback function of readAsjson
session.input.readAsJSON(
// 4. the callback function gets executed
function ( error, json) {
if ( error ) {
session.reject( 'Input is not a valid JSON document' );
return;
}
// 5. only executed if no error occured
inputJson = JSON.stringify(json);
console.debug("Inside: ", inputJson);
}
);
// 3. the console output of inputJson, which was put on 'default'
console.debug("Outside ", inputJson);
This is featured by javaScript as there is only function scope. You can't expect the function parameter inside the readAsJSON()
to execute prior to the console.debug of "outside".
Compare it with throwing 2 boomerangs but the first one takes more time to return.
Similar behavior can be rewritten:
function doMyJSON(json){
// do stuff with json
console.log(json);
}
function getMyJSON(error, json){
if ( error ) { return; }
doMyJSON(json);
}
session.input.readAsJSON(getMyJSON);
Upvotes: 2