You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript新手求助:用Promise实现单选按钮交互及.then用法疑问

问题背景与求助

本人是JavaScript新手,未从事过Web开发相关实习或正式工作。现有如下HTML代码,包含3个单选按钮,h4标签用于显示单选按钮选择后的结果:

<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>

实验要求必须使用Promise实现功能,且Promise对象被拒绝时需调用不同函数。我上周搜索学习了2小时仍无法理解Promise,想知道.then的作用是什么?同时我编写的以下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();
        }
    );
});

解答

一、.then的作用

.then是Promise对象的核心方法,用来指定Promise状态变更后的回调逻辑:

  • 当Promise从**等待(pending)变为完成(fulfilled)**时,执行.then的第一个参数(成功回调函数)
  • 当Promise从**等待(pending)变为拒绝(rejected)**时,执行.then的第二个参数(失败回调函数,可选)
    简单来说,.then就是给Promise安排“成功后做什么”“失败后做什么”的后续操作,让异步或条件判断的结果能被有序处理。

二、代码问题分析与修正

核心问题点

  1. resolve/reject错误传入函数执行结果:你写的resolve(correct())会直接执行correct(),把函数返回的undefined传给resolve,导致Promise刚创建就触发DOM更新,而非通过.then回调执行逻辑。
  2. 重复执行回调:既在resolve/reject里调用了correct()/wrong(),又在.then里再次执行,导致结果被重复设置。
  3. 未确保jQuery依赖:代码使用$但没说明要引入jQuery库,若页面未引入会直接报错。

修正后的代码

方案1(保留jQuery)

// 确保页面已引入jQuery库
$('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(
        // 成功时执行resolve传递的函数
        (callback) => callback(),
        // 失败时执行reject传递的函数
        (callback) => callback()
    );
});

方案2(原生JS,无需jQuery)

如果不想依赖第三方库,用原生JS实现更直观:

// 获取所有单选按钮和结果显示元素
const radios = document.querySelectorAll('input[type=radio][name=3sages]');
const display = document.getElementById("display");

function wrong() {
    display.innerHTML = "Wrong";
}

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

// 给每个单选按钮绑定切换事件
radios.forEach(radio => {
    radio.addEventListener('change', function() {
        let guarantee = new Promise(function(resolve, reject) {
            if (document.getElementById('fav').checked) {
                resolve(correct);
            } else {
                reject(wrong);
            }
        });

        guarantee.then(
            (callback) => callback(),
            (callback) => callback()
        );
    });
});

简化写法(理解核心后可选)

可以不用传递函数,直接在.then回调里调用目标函数,逻辑更清晰:

$('input[type=radio][name=3sages]').change(function() {
    function wrong() {
        $("#display").html("Wrong");
    }

    function correct() {
        $("#display").html("He is my favorite");
    }

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

    // 直接把函数作为.then的参数
    guarantee.then(correct, wrong);
});

内容的提问来源于stack exchange,提问作者Alex Variance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:15:36