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

为何Promise的then回调中x值为undefined?代码问题解析

Promise then回调获取到undefined的原因

问题代码

var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    setTimeout(()=>{
      res(  console.log("done: " + num)  )
    }, 2000);
    console.log("Getting here???" + num);
  });
}


myPromise(myArray[0]).then(x =>  
    console.log("what value: " + x));

疑问

我十分困惑为何console.log("what value: " + x)会打印出x为undefined。我查阅了MDN关于Promise.then的示例,其中then的异步性展示清晰,后续then能获取前序Promise/then传递的值,但我的代码中then回调虽在Promise resolve后执行,却无法拿到对应值,请求解释原因。

解答

问题核心在于你传给res()的参数:你把console.log("done: " + num)的执行结果作为参数传给了res,但console.log函数本身的返回值就是undefined,所以Promise最终resolve的就是undefined,then回调里的x自然就是undefined。

要解决这个问题,你需要把要传递的数值直接传给res,打印操作单独放在外面,修改后的代码如下:

var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    setTimeout(()=>{
      console.log("done: " + num); // 先完成打印
      res(num); // 把num作为resolve的值传递出去
    }, 2000);
    console.log("Getting here???" + num);
  });
}


myPromise(myArray[0]).then(x =>  
    console.log("what value: " + x));

这样修改后,then回调里的x就能拿到num的值,最终会打印出what value: 1。

另外补充一点:代码里的console.log("Getting here???" + num)会先执行,这是因为setTimeout属于异步任务,会被放到任务队列中,等当前同步代码执行完毕后才会触发,这部分是符合Promise异步逻辑的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:32:42