这个.submit()是否有可能等到其他事件完成

时间:2018-02-10 09:48:36

标签: javascript jquery sweetalert2

我有这个代码用jquery编写,也使用sweetalert

$(document).on('click', '#save-task', function() {
  let category      = $('#select-or-enter-category').val();
  let url           = $('#select-or-enter-url').val();

  data = {
    categoryName: category
  };

  axios_post('/check/existing/category', data, function(data) {
    if (data.categoryName == null) {
      $('#cat-id').attr('value', '');

      swal({
        title: "Notice!",
        text: "The category name you entered doesn't exist! Would you like to save it?",
        icon: "warning",
        buttons: true,
        dangerMode: true,
      })
      .then((willSave) => {
        if (willSave) {
          let val = $('#select-or-enter-category').val();

          if (val != '') {
            axios_post('/save-category', {category: val}, function(data) {
              saveCategory(data);
            });
          }
        } else {
          swal("We're not able to save new category!");
        }
      });
    }
  });

  data = {
    url: url
  };

  axios_post('/check/existing/url', data, function(data) {
    if (data.url == null) {
      $('#cat-id').attr('value', '');

      swal({
        title: "Notice!",
        text: "The url you entered doesn't exist! Would you like to save it?",
        icon: "warning",
        buttons: true,
        dangerMode: true,
      })
      .then((willSave) => {
        if (willSave) {
          let val = $('#select-or-enter-url').val();

          if (val != '') {
            // Send a request via post to the server
            axios_post('/save-url', {url: val}, function(data) {
              saveUrl(data);
            });
          }
        } else {
          swal("We're not able to save new category!");
        }
      });
    }
  });

  $('#add-task-form').submit();
});

上述代码工作正常,但此$('#add-task-form').submit();部分将在中间sweetalert事件中提交,但sweetalert未与用户正确交互。

这个$('#add-task-form').submit();是否有可能等到sweetalert事件在那里完成?

1 个答案:

答案 0 :(得分:0)

你应该做“$('#add-task-form')。submit();”在“.then”块中。

如果你必须等待超过1个promise块,你可以将所有promises保存在一个数组中并在“Promise.all()”上进行提交(详情请见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)。您对“swal(...”的调用会返回一个承诺,您可以将其保存在变量中。