As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center提供指导。




已关闭8年。




当我不得不处理异步时,我发现自己在Javascript中写了很多意大利面
应用程序(特别是在处理必须获取所有数据的OpenSocial代码时)
通过JS)。通常的模式是这样的:
  • 用户首次登录应用程序,获取其数据。
  • 对他的数据执行A(例如,通过向服务器发送请求来获得他的 friend )。
  • 在此数据上执行B(例如,将他的 friend 发送到服务器进行某些处理)。
  • 对他的数据执行C(例如,检查服务器响应是否有效,以便我们执行其他操作)。

  • 请注意,此顺序执行路径(1 => 2 => 3 => 4)不太适合异步。的性质
    Ajax使得用户最终等待了很长时间,并且从每一步开始,代码就变得一团糟
    取决于以前的。

    带有代码的示例:
    gadgets.util.registerOnLoadHandler(setupUser())
    ...
    function setupUser() {
      var req = [get data and setup request]
      req.send(some_url, some_data, function(response) { getFriendsFor(response.user) });
    }
    
    function getFriendsFor(user) {
      var friends = [get friends from user]
      var req = [setup request]
      req.send(some_other_url, some_other_data, function(response { validateFriendsResponse(response.friends) });
    }
    
    function validateFriendsResponse(friends) {
      if (friends.valid())
        ...
      loadCanvas();
    }
    

    您会看到每个函数都依赖于前一个函数,更糟糕的是,它必须在
    特定的命令很有用。当您必须添加诸如显示/隐藏加载之类的内容时,情况会变得更糟
    屏幕和其他头,同时用户等待。

    您将如何解决此问题?

    最佳答案

    一种选择是拥有一个显示当前状态的变量,并拥有一个“ Controller ”函数,该函数始终是AJAX回调函数。根据当前状态, Controller 函数将在行中调用下一个函数。为了简化 Controller 功能,我可能会将要调用的功能序列存储在Javascript对象中,因此 Controller 功能所要做的就是查找并传递到序列中的下一个函数。通过使用一个始终是函数参数的Javascript对象(并包含早期AJAX调用返回的所有数据),可以简化此方法。

    例子:

    var user = {};
    var currentState = 1;
    
    var someFunction = function(user) {//stuff here that adds data to user via AJAX, advances currentState, and calls controllerFunction as callback};
    var someOtherFunction = function(user) {//stuff here that does other things to user, advances currentState, and calls controllerFunction as callback}
    
    var functionSequence = {1:someFunction, 2:someOtherFunction}
    
    var controllerFunction = function() {
       //retrieve function from functionSequence based on current state, and call it with user as parameter
    }
    

    10-04 22:48
    查看更多