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

异步函数中布尔值始终返回true的问题排查及代码优化建议

问题原因与代码优化方案

为什么函数始终返回true?

你在call函数里的判断条件写的是if (randomNumber),这里的randomNumber是函数本身——在JavaScript中,函数对象属于「真值」(truthy),所以这个条件永远为true,不会进入else分支。你需要调用这个函数,改成if (randomNumber())才能获取它返回的布尔值,这样才能实现约半数情况触发不同分支的效果。

代码优化建议与优化后的写法

优化点

  • 修复randomNumber的调用问题,确保随机分支生效
  • 所有异步函数调用时添加await,保证执行顺序符合预期(比如响铃结束后再执行接听/答录逻辑)
  • 提取重复逻辑,减少代码冗余(比如通用延迟函数、重复的朋友选择逻辑)
  • 修正拼写错误(BRandon改为Brandon)
  • 函数命名更语义化,提升代码可读性

优化后的代码

const friends = ["John", "Sue", "Matt", "Tim", "Sara", "Lucy"];

// 通用延迟函数,统一处理setTimeout的Promise封装
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

const getRandomFriend = () => friends[Math.floor(Math.random() * friends.length)];

const shouldAnswer = () => Math.floor(Math.random() * 10) < 5;

const ring = async () => {
  await delay(2000);
  console.log("ring ring ring");
};

const playAnsweringMachine = async () => {
  await delay(2000);
  console.log("sorry, we are not available to answer your call.");
};

const answerCall = async () => {
  await delay(2000);
  console.log(`Hey, this is Brandon. May I ask who is calling?`);
};

const introduceCaller = async (friend) => {
  await delay(2000);
  console.log(`this is ${friend}.`);
};

const call = async () => {
  const friend = getRandomFriend();
  console.log(`I think I will call ${friend}`);
  
  await ring();

  if (shouldAnswer()) {
    await answerCall();
    await introduceCaller(friend);
  } else {
    await playAnsweringMachine();
  }
};

call();

优化说明

  • 用delay函数统一处理延迟逻辑,避免重复编写Promise+setTimeout的模板代码
  • 函数命名更贴合语义(比如shouldAnswer比randomNumber更清晰表达用途)
  • 所有异步操作添加await,确保流程按顺序执行(比如响铃结束后才会触发接听/答录,接听后才会报出呼叫者名字)
  • 提取了重复的朋友选择和打印逻辑,减少代码冗余
  • 修正拼写错误,提升代码规范性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 17:39:52