简体   繁体   中英

How to return an async function's value in onclick attribute?

This function returns a Promise.

async function validateStudent(event, reg, pass) {
    if (reg != '' || pass != '') {
        var res = await requestStudent(reg, pass);
        if (res == null) {
            document.getElementById("error").innerText = "Invalid username or password.";
            return false;
        }
        else {
            document.getElementById("HiddenField1").value = res;
            return true;
        }
    }
    else {
        document.getElementById("error").innerText = "Please fill in the form.";
        return false;
    }
}

If I want to use this as an event handler, how will I get its true value without using another async function in the onclick attribute? I want to use this function like this:

<button onclick="return validateStudent('abc', '123')">Send</button>

I tried using return Promise.resolve(validateStudent('abc', '123')) , it did not work.

The issue here appears to be that you are trying to get the button's inline onclick handler to respect and await a promise, which doesn't seem possible at this point in time.

As a result, you will have to alter your approach slightly to be able to achieve your goal. Instead of focusing on making this work by using the default button behavior, you can instead programmatically trigger the form submission when you get your valid promise response.

Change your handler code to return void as you are no longer trying to modify the default button behavior:

async function validateStudent(event, reg, pass) {
    if (reg != '' || pass != '') {
        var res = await requestStudent(reg, pass);
        if (res == null) {
            document.getElementById("error").innerText = "Invalid username or password.";
        }
        else {
            document.getElementById("HiddenField1").value = res;
            document.getElementsByTagName("form")[0].submit(); // Add this line to submit form after hidden input is filled
        }
    }
    else {
        document.getElementById("error").innerText = "Please fill in the form.";
    }
}

And finally change your button to the following:

<button type="button" onclick="validateStudent('abc', '123')">Send</button>

Note that I added type="button" to avoid the default form submission behavior (if you omit the button type it becomes type="submit" by default when in a form context). I also removed the return as the button's onclick no longer cares about the return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM