简体   繁体   中英

Asynchronous Javascript and promises

I am still a newbie at JavaScript and have not done any internships or formal work on web development.

The HTML have 3 radio buttons and the h4 tag is for displaying some text/result based on radio button selection.

HTML:

<p>The 3 sages of the apocalypse</p>
<input id="cat" type="radio" name="3sages">
<label >Luceila of the South</label><br>
<input id="fav" type="radio" name="3sages">
<label >Isley of the North</label><br>
<input id="split" type="radio" name="3sages">
<label >Riful of the west</label><br>
    
<h4 id="display"></h4>

The lab requirements is such that I must use promises and when the promise object is rejected a different function call must take place. Promise is hard to understand as I have googled for 2 hours last week and cannot understand. What purpose does.then serve? Is it using the promise object?

JavaScript (not working):

$('input[type=radio][name=3sages]').change(function()
{
    function wrong()
    {
        const write = document.getElementById("display");
        write.innerHTML = "Wrong";
    }

    function correct()
    {
        const write = document.getElementById("display");
        write.innerHTML = "He is my favorite";
    }

    let guarantee = new Promise(function(resolve,reject) {
        if ($('#fav').is(':checked'))
        {
            resolve(correct());
        }
        else
        {
            reject(wrong());
        }
    });

    guarantee.then( 
        function() 
        {
            correct();
        },
        function() 
        {
            wrong();
        }
    );
});

JavaScript (not working)

Actually your code works fine (but read on). Make sure you include jQuery, and that your script is executed after the document has loaded - so place your script at the bottom of the page. Here is your code in your runnable snippet:

 $('input[type=radio][name=3sages]').change(function() { function wrong() { const write = document.getElementById("display"); write.innerHTML = "Wrong"; } function correct() { const write = document.getElementById("display"); write.innerHTML = "He is my favorite"; } let guarantee = new Promise(function(resolve,reject) { if ($('#fav').is(':checked')) { resolve(correct()); } else { reject(wrong()); } }); guarantee.then( function() { correct(); }, function() { wrong(); } ); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>The 3 sages of the apocalypse</p> <input id="cat" type="radio" name="3sages"> <label >Luceila of the South</label><br> <input id="fav" type="radio" name="3sages"> <label >Isley of the North</label><br> <input id="split" type="radio" name="3sages"> <label >Riful of the west</label><br> <h4 id="display"></h4>

I must use promises

Honestly, it makes no sense to use promises when there is no asynchronous behaviour. In your code the promise is created at a moment that all needed information is available, and there is nothing to await asynchronously.

If this is indeed the intended exercise, so be it, but if you want to look to something that really is asynchronous then look to awaiting the user's input. That part is asynchronous -- you don't know beforehand when the user will click that radio button. That is where a promise can be used. This comes down to promisifying the jQuery .click method (or more generally, its .on method). As a promise is about capturing one event, and event listeners trigger on each repeated event, you would need to only listen to one event (using jQuery's .one method) and then when it fires, create a new promise for the next event occurrence.

Here is how that would look:

 // Generic function to get a promise of a certain event on a selected element function promiseEvent(selector, event) { return new Promise(resolve => $(selector).one(event, resolve)); } // Specific function to get a promise for the user selecting an answer function promiseAnswer() { return promiseEvent('input[type=radio][name=3sages]', 'change'); } // Create the promise and listen for when it resolves promiseAnswer().then(processChoice); function processChoice() { // React to the user's choice $("#display").text( $('#fav').is(':checked')? "He is my favorite": "Wrong" ); // Create the promise again and listen when it resolves promiseAnswer().then(processChoice); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>The 3 sages of the apocalypse</p> <input id="cat" type="radio" name="3sages"> <label >Luceila of the South</label><br> <input id="fav" type="radio" name="3sages"> <label >Isley of the North</label><br> <input id="split" type="radio" name="3sages"> <label >Riful of the west</label><br> <h4 id="display"></h4>

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