Search code examples
javascriptasync-awaitevent-listenerpreventdefault

Event.preventdefault() after async function


In order to prevent bs-stepper from going to the next step, I'm using this eventhandler approach. Unfortunatley this approach seems not working with an async function like isFaceValid()... Both version below are not working. No matter if I use async key word or not.

Is it even possible what I'm trying to achieve?

At the moment I assume I have to stick with this event handler approach, I don't see an other way to work with bs-stepper https://github.com/Johann-S/bs-stepper

stepperFormEl.addEventListener('show.bs-stepper', function(event) {
    form.classList.remove('was-validated')
    var nextStep = event.detail.indexStep
    var currentStep = nextStep

    if (currentStep > 0) {
        currentStep--
    }

    var stepperPan = stepperPanList[currentStep]

    if ((stepperPan.getAttribute('id') === 'test-form-1' && (!$('#inputUserImage').get(0).files.length)) ||
        (stepperPan.getAttribute('id') === 'test-form-1' && !anAsyncFunction())) {
        event.preventDefault();
        form.classList.add('was-validated')
    }
})


stepperFormEl.addEventListener('show.bs-stepper', async function(event) {
    form.classList.remove('was-validated')
    var nextStep = event.detail.indexStep
    var currentStep = nextStep

    if (currentStep > 0) {
        currentStep--
    }

    var stepperPan = stepperPanList[currentStep]

    if ((stepperPan.getAttribute('id') === 'test-form-1' && (!$('#inputUserImage').get(0).files.length)) ||
        (stepperPan.getAttribute('id') === 'test-form-1' && !await anAsyncFunction())) {
        event.preventDefault();
        form.classList.add('was-validated')
    }
})

Solution

  • You can avoid using the event handler approach, bs-stepper comes from with various available public methods, such as "next" or "previous". See: https://github.com/Johann-S/bs-stepper#next

    So you can do something like

    if (!await anAsyncFunction()) {
      return;
    }
    
    bsStepper.next();
    

    like that you'll be able to prevent showing the next step