2016-09-16 73 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

謝謝,這是非常有益的! –