2016-09-16 60 views
1

我是Datapower网关脚本(和Javascript)的新手,以下情况完全让我感到困惑。看:在Datapower(GatewayScript)中使用Javascript的范围

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); 

在DataPower的控制台将以下内容:

“内:{长JSON字符串}”

“外:默认”

它完全打破了我的心灵,扭曲我的了解变量范围。是javascript,datapower脚本实现的功能还是什么?

UPD。而另一位脑裂的事情:

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)); 

控制台结果:

  1. :(!原文如此) “FUNC结果默认”

  2. “之前:默认”

  3. “ After:--json string--“

如何在函数执行前打印函数结果?

回答

2

因为session.input.readAsJson();需要更多的时间来执行。如果我们在这个和平的代码中按顺序执行事件编号:

// 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); 

这是javaScript的特色,因为只有函数作用域。您不能期望readAsJSON()中的函数参数在console.debug“outside”之前执行。

与投掷2个回飞镖比较,但第一个需要更多时间返回。

类似的行为可以被改写:

function doMyJSON(json){ 
    // do stuff with json 
    console.log(json); 
} 

function getMyJSON(error, json){ 
    if (error) { return; } 
    doMyJSON(json); 
} 

session.input.readAsJSON(getMyJSON); 
+0

谢谢你的解释,但我怎么可以通过该JSON字符串已经摆在** ** inputJson可变 –

+1

通过移动它内部的控制台确保像你一样回调。或者如果你真的想保持它分开,试着找到关于“延迟”或“异步”的javaScript的信息。在第5步中,您可以调用自己的函数,将json作为参数传递,并且您又可以重新开始。 –

+0

谢谢,这是非常有益的! –