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

JavaScript Async/Await代码疑问:为何变量a输出为空字符串?

为什么async/await代码中变量a输出为空字符串?

你的代码如下:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("here");
    }, 15000);
  });
}

async function asyncCall() {

  let a = ""

  const result1 = await resolveAfter2Seconds();
  const result2 = await resolveAfter2Seconds();
  a.concat(result1, result2)
  console.log('calling');
  console.log(a)

}

asyncCall();
console.log("tmkoc")

你的await执行逻辑是对的,代码确实会等两个Promise都完成后再执行拼接操作,result1和result2都能拿到"here"值。问题出在字符串的特性上:

JavaScript里的字符串是不可变类型,concat()方法不会修改原变量a,而是返回一个全新的拼接后的字符串。你只是调用了concat()但没有把返回值重新赋值给a,所以a始终是初始的空字符串。

修正方案

把拼接代码改成赋值形式即可:

// 方案1:使用concat并赋值
a = a.concat(result1, result2);

// 方案2:更简洁的+=写法
a += result1 + result2;

修正后的完整代码:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("here");
    }, 15000);
  });
}

async function asyncCall() {

  let a = ""

  const result1 = await resolveAfter2Seconds();
  const result2 = await resolveAfter2Seconds();
  a = a.concat(result1, result2); // 这里修改为赋值
  console.log('calling');
  console.log(a) // 现在会输出"herehere"

}

asyncCall();
console.log("tmkoc")

另外补充:console.log("tmkoc")会先于console.log('calling')输出,这是因为asyncCall是异步函数,调用后会先执行同步代码,等Promise的定时器完成后才会执行asyncCall内部的后续逻辑,但这和a为空的问题无关。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 04:15:09