如何使用 JavaScript 等待 onchange 事件中的 Promise 完成?

Jun*_*ior 5 javascript jquery promise

我需要手动触发change菜单上的事件。但是然后我需要等到change事件完成执行然后我才能执行操作。

这是我试图在代码中执行的操作

$('#menu').change(function(){

  // do some work
  // make multiple AJAX calls....

});

$('#button').click(function(){

   $('#menu').val(5).change(); // once change is completed I want to do some logic here.
});
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的,但似乎没有等待change()事件完成。

$('#button').click(function(){

   $('#menu').val(5).change().promise().done(function(){
      // do some work after the change() event is completed..
   });
});
Run Code Online (Sandbox Code Playgroud)

在更改事件完成之前如何正确执行代码?

更新

我尝试了以下方法,但似乎仍然不起作用

$('#menu').change(function(){

     makeAjaxCalls($(this).val());

});


$('#button').click(function(){

   makeAjaxCalls(5, function(){
      // do some work after the makeAjaxCalls() is completed..
   });
});

function makeAjaxCalls(id, callback) {
    var task = $.Deferred(function(){
         // Make all ajax calls here...
    });

    $.when(task).then(function() {
        if ($.isFunction(callback)) {
            callback();
        }
    }).catch(function (error) {
        console.log('something wrong... ', error);
    });
}
Run Code Online (Sandbox Code Playgroud)

Avc*_*vcS 1

您想要调用一个对菜单更改和按钮单击进行异步调用的函数。有一个简单的解决方案,创建一个函数来读取菜单的值并返回一个承诺,并在两个事件中使用它。

function makeAjaxCalls() {
    var menuValue = $('#menu').val();
    // Run some ajax calls based on menuValue and return the promise
    return Promise.resolve()
}

$('#menu').change(makeAjaxCalls);
$('#button').click(function(){
    $('#menu').val(5);
    makeAjaxCalls().then(function() {
        // Do something after ajax calls completed
    });
});
Run Code Online (Sandbox Code Playgroud)