Datapower (GatewayScript) 中 Javascript 的范围

Scope of Javascript in Datapower (GatewayScript)

我是 Datapower Gateway 脚本(和 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 控制台中将显示以下内容:

"Inside: { long json string }"

"Outside: default"

它完全打破了我的想法并扭曲了我对变量范围的了解。它是 javascript 的功能、datapower 脚本实现还是什么?

更新。还有一个脑洞大开的事情:

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 result: default"(原文如此!)

  2. "Before: default"

  3. "After: --json string--"

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

因为 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() 中的函数参数在 "outside" 的 console.debug 之前执行。

将它与投掷 2 个回旋镖进行比较,但第一个回旋镖需要更多时间 return。

可以重写类似的行为:

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

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

session.input.readAsJSON(getMyJSON);