Javascript:如何等待eval函数



我正在进行一个项目,该项目从分块代码块绘制对象。因此,将生成一个代码字符串,该字符串在下面的函数中进行求值。在使用eval函数运行的代码中,所有创建的对象都存储在一个数组(对象(中。我的问题是,在alert(objects.length(可以使用更新后的对象数组之前,代码没有得到完全评估(因此,它的警报为零,因为我以前重置过数组(。因此警报应该等待eval函数。你能帮我解决这个问题吗?

function paintFromCode() {
slideTo('konva_box');
setTimeout(function(){
deleteObjects();
let code = Blockly.JavaScript.workspaceToCode(workspace);
try {
code = "let t = 0;" + code;
eval(code);
} catch (e) {
alert(e);
}
layer.add(pospanel);
alert(objects.length);
}, 1000);
}

创建代码的部分功能:

let code = "setTimeout( function() {" +
"objects['" + text_identifier.toUpperCase() + "'] = new Konva.Circle({x: 50, y: 100, radius: 50, fill: '#00ff00'});" +
"layer.add(objects['" + text_identifier.toUpperCase() + "']);" +
"layer.draw();" +
"}, speed * t);" + 
"t = t + 1;";
return code;

按照上面编写代码的方式,似乎可以控制layer。运行代码块的最后会调用layer.draw()。您可以重新定义draw来调用alert语句。

// store original draw function
const orginalDraw = layer.draw;
layer.draw = function() {
originalDraw();
alert('draw has just been called');
}
try {
code = "let t = 0;" + code;
eval(code);
} catch (e) { alert(e); }

EDIT我的初始响应不必要地复杂。。。假设setTimeout发生在Blockly Code Blocks返回的代码字符串中,建议截取setTimeout函数,并在那里插入超时后处理。(另一种选择是搜索并替换Blockly Code Blocks代码字符串中的setTimeout条目,替换为类似的自定义setTimeout函数,该函数也执行超时后处理。(

// Simulate ==> let code = Blockly.JavaScript.workspaceToCode(workspace);
// with an embedded setTimeout in the code to be eval-ed.
let code = `
setTimeout( () => alert('Blocky!'), 2000);
`;
// Define the custom function to run once the setTimeout is complete.
var a = 0;
function postTimeout( x ) {
console.log( a );
a = x;
console.log( a );
alert( a );
}
// Finally, execute the "Blocky" code. But first, intercept the setTimeout
// function and afterwards reset it.  Alternatively, one can search and
// replace 'setTimeout(' in the Blocky code, replacing with similar 
// intercepting function.
const stf = setTimeout;
setTimeout = function(f,ms) {
return stf( () => { f(); postTimeout( 42 ) }, ms)
};

eval( code );
setTimeout = stf;

运行此代码段后,在2秒内,alert('Blocky!')将启动,用setTimeout函数表示Blocky代码,然后紧接着,自定义postTimeout函数将启动,模拟

layer.add(pospanel);
alert(objects.length);

在问题中。

我已经将CCD_ 7包括在内;Blocky";code变量中的javascript。。。

我遇到了同样的问题,以下是我如何处理

try { 
eval("(async () => {"+code+"})()");
}
catch (e) {
alert(e);
}

代码在myArr1中按函数分割,在每个函数后我添加

let wait='); await this.waitfunction(500);';
for (var i=0; i<myArr1.length-1;i++){
let tex=
myArr1[i].concat(wait);
b[i]=tex;

}

这是我的等待功能((:

waitfunction(ms){
return new Promise(resolve => {
setTimeout(()=>resolve(''),ms)
});
}

我知道那很长,但它有效

最新更新