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

How to async await with jQuery sortable receive and update?

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

我还有一个用于同一个可排序列表的 update 函数,在任何更改时,它会循环遍历列表以获取 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
    }

我怎样才能让 'receive' 中的函数完成,然后再继续 'update' 中的函数?或者有更好的方法吗?

编辑:

样本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. 里面'update'

        if (receiveInProgress == true) {
            console.log("Receive in progress! Update will happen on its own.")
        } else {
            updateComponentOrderInDB();
        }
    
  4. 现在,在 'receive' 开始时,我将 receiveInProgress 设置为 true,在 Ajax 调用结束时,我将其设置回 false 并且 运行 updateComponentOrderInDB()。现在所有工作都按预期顺序进行!

'receive' 和 'update' 回调由可排序小部件同步调用。 'wait' receive 函数中的异步调用无法在 'update' 触发之前完成。

你应该以不同的方式处理这个问题。您可能根本不需要 'update' 函数。在 Ajax 调用完成后,您可以在 createNewComponentInDB 函数中触发 'sort'。我假设您正在 Ajax 调用的回调中执行 $(newItem).attr('id', response);,只需将您的排序逻辑紧跟在这一行之后。