简体   繁体   English

使Javascript调用同步

[英]Making Javascript Calls Synchronous

I'm a bit newer to javascript and am having a hard time figuring out how to work the callbacks in some existing code. 我对javascript较新,并且很难弄清楚如何在一些现有代码中使用回调。

Setup: I have a util.js that contains a lot of helper functions like function 设置:我有一个util.js,其中包含很多辅助函数,例如function

getComments(packageId, successCallback, failCallback, userId)

and

function getActionMemo(packageId, versionId, successCallback, failCallback)

that return the results of an ajax call to the successCallback. 将ajax调用的结果返回给successCallback。

What I need to make, and what I'm struggling with, is a function that amasses the data of the helper functions and to make it more fun, I have a specific order I need to call the helper functions in because there are some data dependencies. 我需要做的是我正在苦苦挣扎的一个函数,它可以对帮助程序函数的数据进行评估,并使之更加有趣,我需要按特定的顺序调用帮助程序函数,因为其中存在一些数据依赖性。

I can hack this by basically copying the code out of the helper functions into a new function and chaining the .done from the ajax call, but this seems like horrible practice. 我可以通过将代码从辅助函数中复制到新函数中并从ajax调用中链接.done来进行破解,但这似乎是一种可怕的做法。 Is there a cleaner way? 有没有更清洁的方法?

Thanks, Erin 谢谢,艾琳

Looks like promises could be a solution to your problem. 看起来诺言可以解决您的问题。 Please read https://www.promisejs.org/ 请阅读https://www.promisejs.org/

You have a list of actions, these actions are stored in an array or into the html I suppose? 您有一个动作列表,这些动作存储在数组中还是我想的HTML中?

Create an index, starting at 0. 创建一个从0开始的索引。

Then in your function you add 1 each time you start the function, select the new action and make your ajax call. 然后,在函数中,每次启动函数时加1,选择新动作并进行ajax调用。

I met your scenario once and will detail the method I used if this doesn't help you. 我曾经遇到过您的情况,如果无法解决问题,将详细说明我使用的方法。

If it helps, I recently took the first release of the Rogue game written for UNIX in C and rewrote it for javascript to work in a browser. 如果有帮助,我最近拿了用C语言为UNIX编写的Rogue游戏的第一版,并重写了它,以便javascript在浏览器中工作。 I used a technic called continuation to be able to wait for key entry by the user because in javascript the are no interrupts. 我使用一种称为延续的技术来等待用户输入密钥,因为在javascript中没有中断。

So I would have a piece of code like this: 所以我会有一段这样的代码:

void function f() {

  // ... first part

  ch = getchar();

  // ... second part

}

that would be transformed in 那将被转化为

function f() {

  // ... first part

  var ch = getchar(f_cont1);

  return;
  // the execution stops here 

  function f_cont1 () {

    // ... second part
  }
}

the continuation is then stored to be reuse on a keypressed event. 然后继续存储以在按键事件中重用。 With closures everything would be restarted where it stoped. 使用闭包,一切将在停止的地方重新开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM