【问题标题】:Indesign and Extendscript: Multiple functions, loops, and timing. Function called in a loop, not in syncIndesign 和 Extendscript:多种功能、循环和时序。循环调用的函数,不同步
【发布时间】:2019-05-16 13:50:28
【问题描述】:

关键问题是循环中的函数不同步。我没有得到正确的var myDimensions,除非我包含 alert() 来减慢进程。我不确定是否需要使用回调。我阅读了它们并发现它们令人困惑,我想避免回调地狱。发生的事情是,在循环中运行函数时,我的其他一些函数调用不同步。 我将此 JavaScript 编写为 Adob​​e InDesign 的 Extendscript,因此 Extendscript 不包含现代 JS。

在函数中添加alert() 以返回值以确认我得到正确的值后,我发现了计时问题。如果我添加 alert() 它会导致延迟,从而使代码正确运行。当我删除 alert() 它再次失败。为了简洁起见,我尝试简化下面的代码,而不是粘贴完整的 1,500 行文件。

function calculateSomething(podValue){
  return podValue + 1;
}

function doPodStuff(value){
  return value;
}

function getDimensions(calculation){
  return calculation * 2;
}

function pod(value, count){
  var podStuff;
  var calculation;
  var myDimensions;
  podStuff = doPodStuff(value);
  calculation = calculateSomething(podStuff):
  myDimensions = getDimensions(calculation);
  /* this is where my timing is off and podStuff and calculation get out of sync,
  I determined this after placing an alert(myDimensions) right here If I add the alert(),
  the delay makes it work, when I remove alert() it fails again.
  */
  return myDimensions;
}

function row(value, count){
  var myPod;
  for(var i = 0; i < count; i++){
    myPod = pod(value, 2);
  }
  return myPod;
}

row('foobar', 4);

我的目标是让pod() 函数在for() 循环中运行,但不会出现故障。如何同步或确保时间正确?

【问题讨论】:

  • 前三个函数是否返回相同的value?似乎不太可能(如果属实,则多余)并使事情变得混乱。您可能需要一些时间来read this 寻求帮助以创建更清晰的 MCVE
  • 如果问题是在调用 geDimensions 之后出现的,那么问题很可能出在 getDimensions 定义中。您是否在这些函数中使用共享全局变量?
  • @cybernetic.nomad 对不起,我想我为了简洁而牺牲了可读性。那在我身上。如果有帮助,我可以编辑。我一定会阅读您的链接。
  • @Miguel,经过一番思考,似乎从循环中运行函数会导致计时停止,所以我正在考虑如何格式化以同步运行,而不是异步。由于我在 InDesign 中,我通常不能像在其他 JavaScript 项目中那样使用 Promise,并且我试图避免回调地狱。

标签: javascript adobe adobe-indesign extendscript


【解决方案1】:

你可以尝试链接你的函数:

function pod(value, count) {
    return getDimensions(calculateSomething(doPodStuff(value))) }

在任何情况下,您都可以使用$.sleep(1000) 而不是alert("...") 来减慢您的脚本速度。

【讨论】:

    猜你喜欢
    • 2018-08-23
    • 2021-08-02
    • 1970-01-01
    • 2021-03-15
    • 2017-06-25
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多