如何异步等待jQuery可排序接收和更新?

问题描述 投票:1回答:1

我使用sortable的receive来接收可拖动列表中的元素。发生这种情况时,使用Ajax调用将元素的数据发送到服务器,并在数据库中创建条目。完成后,将返回一个id并将其添加到新元素中。

我还有一个相同的可排序列表的更新函数,在任何更改时,它循环遍历列表以获取ID并进行另一个Ajax调用以更新值。

问题是进程混合并且更新函数在加载新元素的id之前抓取所有id,这意味着它将缺少新元素的id。

$( ".sort1" ).sortable({
    connectWith: ".sortable-sections",
    stack: ".sortable-sections ul",
    cancel: "input,textarea,button,select,option,[contenteditable],.editorArea,.unsortable",
    receive: function(event, ui) {
        // lots of things happen
        createNewComponentInDB(data); 
        // leads to the ajax post which if successful $(newItem).attr('id', response); 
    },
    update: function(event, ui) {
        // grab list items indexes and ids
        // ajax post to update in database
    }

在继续“更新”中的功能之前,我该怎么做才能让“接收”中的功能完成?或者有更好的方法吗?

编辑:

示例HTML:

<ul class="space-sections sortable-sections sort1 ui-sortable"> 
    <li class="space-section drag draggable-item ui-sortable-handle" id="5c920e65a7917045fbf62d45" data-component-type="list"> 
    /* ... lots of nested stuff */
    </li>
    <li class="space-section drag draggable-item ui-sortable-handle" id="5c920e6ca7917045fbf62d46" data-component-type="list"> 
    /* ... lots of nested stuff */
    </li>
</ul>

更新解决方案:

感谢与@ elem4th的对话,我能够通过使用'flag concept'来解决这个问题。

  1. 我创建了一个变量receiveInProgress并将其设置为false。
  2. 然后将'update'中的函数转换为独立函数updateComponentOrderInDB()
  3. 内部'更新' if (receiveInProgress == true) { console.log("Receive in progress! Update will happen on its own.") } else { updateComponentOrderInDB(); }
  4. 现在,在'receive'的开头,我将receiveInProgress设置为true,并且在Ajax调用结束时,我将其设置为false并运行updateComponentOrderInDB()。现在一切按预期顺序排列!
jquery node.js ajax async-await jquery-ui-sortable
1个回答
2
投票

“可接收”和“更新”回调由可排序小部件同步调用。在“更新”触发之前,无法“等待”receive函数中的异步调用完成。

你应该采用不同的方法。您可能根本不需要“更新”功能。在Ajax调用完成后,您可以在createNewComponentInDB函数中触发“排序”。我假设您在Ajax调用的回调中执行$(newItem).attr('id', response);,只需在此行之后立即放置排序逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.