gpt4 book ai didi

javascript - Datapower 中 Javascript 的范围 (GatewayScript)

转载 作者:行者123 更新时间:2023-11-30 15:49:58 24 4
gpt4 key购买 nike

我是 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 控制台中将如下:

“内部:{长json字符串}”

“外部:默认”

它完全打破了我的想法并扭曲了我对变量范围的了解。它是 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. “函数结果:默认值”(原文如此!)

  2. “之前:默认”

  3. “之后:--json 字符串--”

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

最佳答案

因为 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 之前执行。

将其与 throw 2 个回旋镖进行比较,但第一个回旋镖需要更多时间才能返回。

可以重写类似的行为:

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

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

session.input.readAsJSON(getMyJSON);

关于javascript - Datapower 中 Javascript 的范围 (GatewayScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39527227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com