简体   繁体   English

异步 Javascript 和承诺

[英]Asynchronous Javascript and promises

I am still a newbie at JavaScript and have not done any internships or formal work on web development.我还是 JavaScript 的新手,还没有在 web 开发方面做过任何实习或正式工作。

The HTML have 3 radio buttons and the h4 tag is for displaying some text/result based on radio button selection. HTML 有 3 个单选按钮,h4 标签用于根据单选按钮选择显示一些文本/结果。

HTML: 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 object 被拒绝时,必须进行不同的 function 调用。 Promise is hard to understand as I have googled for 2 hours last week and cannot understand. Promise 很难理解,因为我上周用谷歌搜索了 2 个小时,无法理解。 What purpose does.then serve?那么.then 有什么作用? Is it using the promise object?是否使用 promise object?

JavaScript (not working): JavaScript(不工作):

$('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) JavaScript(不工作)

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.确保您包含 jQuery,并且您的脚本在文档加载后执行 - 所以将您的脚本放在页面底部。 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.老实说,在没有异步行为的情况下使用 Promise 是没有意义的。 In your code the promise is created at a moment that all needed information is available, and there is nothing to await asynchronously.在您的代码中,promise 是在所有需要的信息都可用的时刻创建的,并且没有什么可以异步等待。

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.这就是可以使用 promise 的地方。 This comes down to promisifying the jQuery .click method (or more generally, its .on method).这归结为承诺 jQuery .click方法(或更一般地说,它的.on方法)。 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.由于 promise 是关于捕获一个事件,并且事件侦听器会在每个重复事件上触发,因此您只需要侦听一个事件(使用 jQuery 的.one方法),然后当它触发时,为下一个事件发生创建一个新的 promise。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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