【问题标题】:Async Problems with jQuery & JavascriptjQuery 和 Javascript 的异步问题
【发布时间】:2014-05-06 15:12:16
【问题描述】:

我在兜圈子,似乎无法从 Stack 或 Google 上当前可用的资源中找出解决方案。一定有一些明显的东西我错过了,也许你能帮忙?

故事摘要:

  • 单击时会启动一个 javascript 函数,并在我们的数据库中创建一个新联系人。
  • 然后在成功创建后调用其他函数,以根据一些复选框在必要时切换某些设置。
  • 目前正在异步进行调用,导致只有最后一次函数调用才能成功更新联系人。
  • 我这辈子都不能接到一个接一个上班的电话。
  • 每次调用都会在成功完成后返回一个 JsonResult,如果这有帮助的话(应用程序的其他区域需要。

代码目前如下所示: function CreateClicked(){ Contact.Create(**bunch of params**, function(data){ if(data.success) { togglePrimary(data.newId); toggleBilling(data.newId); toggleTechnical(data.newId); toggleBalance(data.newId); toggleSecurity(data.newId); toggleMarketing(data.newId); Modal.Load(**loads a modal view**); } } }

切换功能如下所示: function togglePrimary(id) { if ($("#contact_admin_primaryrole").prop('checked')) {Contact.TogglePrimaryRole(id);} }

调用如下所示的控制器函数:

public JsonResult TogglePrimaryRole(int contactId){ try{ var c = new Contact(contactId); c.IsPrimaryContact = !c.IsPrimaryContact; c.Update(AuthenticatedUser.Username, !c.IsPrimaryContact); return Json(JSONResponseFactory.SuccessResponse("Contact updated successfully")); } catch (Exception ex){ return Json(JSONResponseFactory.ErrorResponse(ex.Message)); } }

我应该如何进行设置,以使每个切换功能在前一个功能完成并返回 Json 响应之前不会启动,无论成功与否?

有什么想法吗?

干杯, 德兹

【问题讨论】:

    标签: javascript json asp.net-mvc-3 asynchronous synchronous


    【解决方案1】:

    使用 jQuery 承诺应该会有所帮助:

    togglePrimary(data.newId).then(toggleBilling(data.newId)).then(toggleTechnical(data.newId)
    

    等等

    仅当最后一个函数成功时才会运行下一个函数。如果您想调用与结果无关的函数,请使用 always() 而不是 then()

    togglePrimary(data.newId).always(toggleBilling(data.newId)).always(toggleTechnical(data.newId)
    

    这将需要引用 jquery 1.6 或更高版本。要从 CDN 引用,请添加以下内容

    <script src="http://code.jquery.com/jquery-1.9.0.js"></script>
    

    【讨论】:

    • 感谢您的建议。尝试这两种方法现在可以正确执行第一个函数,但是我在其余的函数上得到以下错误:“Uncaught TypeError: Cannot read property 'always' of undefined”
    • 你引用了 Jquery 吗?相应地更新了我的答案
    • 是的,文档中引用了 jQuery,但实际上似乎并不喜欢 this() 或 always() 方法。 ://
    【解决方案2】:

    我似乎无法使用 Promise 或带有回调的 javascript 函数链接...所以我将每个状态的值转换为字符串数组并在控制器中对其进行解析!

    感谢您的帮助:)

    【讨论】:

      猜你喜欢
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      相关资源
      最近更新 更多