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

Promise代码疑问:为何输出undefined及命名函数无法正常工作?

问题解答

先看执行的代码:

function my_function_for_good_response(response){
    console.log(response)
}

my_promise_function(1)
    .then((response) => console.log(response))
    .catch((response) => console.log(response))

my_promise_function(0)
    .then(my_function_for_good_response())
    .catch((response) => console.log(response))

function my_promise_function(parameter){
    return new Promise((resolve, reject) => {
        if (parameter>0){
            console.log()
            resolve("good response")
        }else{
            reject('bad response')
        }
    })
}

控制台输出:

undefined
good response
bad response

1. 控制台首行的undefined是怎么来的?

你在第二个my_promise_function(0)的then里写了my_function_for_good_response()——这里是直接调用了这个函数,而不是把它作为回调传给then。这个函数内部只有console.log(response),没有返回值,所以调用后会返回undefined,这个返回值被同步打印到了控制台,就是首行的undefined。

2. 为什么undefined出现在首行而非第二行?

JavaScript代码执行顺序是先跑同步任务,再处理异步微任务(比如Promise的then/catch回调)。my_function_for_good_response()是同步执行的,所以它的返回值undefined会先被输出;而两个my_promise_function里的resolve和reject触发的回调都是异步微任务,要等所有同步代码跑完才会执行,所以后面的good response和bad response会在undefined之后输出。

3. 命名函数为什么无法正常工作?

then方法需要接收一个函数作为回调,当Promise状态变为resolved时才会调用这个函数并传入响应值。但你写的是then(my_function_for_good_response()),这是直接执行了函数,把执行结果(undefined)传给了then,而不是传函数本身。正确的写法应该是then(my_function_for_good_response)(去掉括号),这样当Promise resolve时,才会自动调用这个函数并把response传进去。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:25:18