如何在jquery click函数中等待确认

bq9c1y66  于 12个月前  发布在  jQuery
关注(0)|答案(2)|浏览(113)

嗨,我有一个要求,我需要等待确认完成。

**注意:**我不能在click(大块)内触摸我的前辈的下面代码或用.then(function(){..}); Package 它们
这是我尝试过的,但给出了错误:

async function showConfirmationAndWait(){
    $.alertable.confirm('You sure?').then(function() {
      return new Promise(function(res,rej){
           res({confirmed:true});
      });
    }, function() {
       return new Promise(function(res,rej){
           res({confirmed:false});
      });  
    });
}  

$('#await').on('click',function(){
    var promiseObj =  await showConfirmationAndWait(); //throwing error
    
    //...... big code with its own function call that i don't want to touch
 });

字符串

**问题:**我想等到确认完成,而不是用.then(function(){..}); Package 整个代码
以下是我尝试过的:

async function showConfirmationAndWait(){
    $.alertable.confirm('You sure?').then(function() {
      return new Promise(function(res,rej){
           res({confirmed:true});
      });
    }, function() {
       return new Promise(function(res,rej){
           res({confirmed:false});
      });  
    });
}  

$(function(){
    $('#await').on('click',function(){
        var promiseObj =  await showConfirmationAndWait(); //commented due to error
         console.log('after await promiseObj',promiseObj);
      
       //...... big code with its own function call that i don't want to touch
    });
});
<link href="https://cdn.rawgit.com/claviska/jquery-alertable/master/jquery.alertable.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></script>
<script src="https://rawgit.com/claviska/jquery-alertable/master/jquery.alertable.min.js"></script>

<button id="await">Show confirmation wait and proceed next line</button>

的数据

lyfkaqu1

lyfkaqu11#

您需要重写showConfirmationAndWait以实际等待确认并返回结果。
同时将整个处理程序标记为async

async function showConfirmationAndWait() {
  try {
    await $.alertable.confirm('You sure?');
    return true
  } catch {
    return false
  }
}

$(function() {
  $('#await').on('click', async function() {
    var promiseObj = await showConfirmationAndWait();
    console.log('after await promiseObj', promiseObj);

    //...... big code with its own function call that i don't want to touch
    console.log('Some scary logic goes here. It should be printed after confirmation.');

  });
});

个字符

prdp8dxp

prdp8dxp2#

这是行不通的

const form = $('form')
form.find('[type="submit"]').click(async event => {
   event.preventDefault() // will NOT WORK
   await myfunction()
   form.submit()
})

字符串
这将工作

const form = $('form')
form.find('[type="submit"]').click(event => {
   event.preventDefault()
   (async function() {
       await myfunction()
       form.submit()
   })()
})

相关问题