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

JavaScript中await使用疑问:异步函数练习返回数字需求实现

修正你的JavaScript异步函数实现

函数f的问题与修复

  1. Promise状态未正确触发:你在Promise执行器里直接return value,这不会让Promise进入resolved状态,必须调用resolve(value)才能完成异步结果的传递。更简洁的方式是直接用async关键字定义函数——async函数会自动把返回值包装为resolved Promise,抛出的错误会自动包装为rejected Promise,无需手动实例化Promise。
  2. 数字校验逻辑有漏洞:!isNaN(value)会把空字符串、布尔值这类非数字类型误判为有效数字,改用typeof value === 'number' && !isNaN(value)能严格校验输入是否为有效数字。
  3. 错误处理规范调整:在async函数里直接throw错误即可,会被自动转为rejected Promise,完全符合题目要求的抛出错误逻辑。

函数g的问题与修复

  1. 未满足async函数定义要求:题目明确要求g是async函数,必须添加async关键字。
  2. 参数使用逻辑错误:你在then回调里直接用了原始的value参数,应该依赖f返回的resolved值(即回调参数na_loga),确保逻辑基于异步操作的结果而非原始输入。
  3. 异常处理不符合需求:题目要求捕获异常后返回错误消息,而非重新抛出,所以catch块里要return错误内容,不能throw。
  4. 代码可读性优化:用await替代then/catch链式调用,让异步逻辑更直观易懂。

修复后的完整代码

/**
 * TODO: implement an *async* function 'f' that returns the value of a parameter inside a Promise
 * @param {number} value, must be a number, isNaN() is useful here
 * @throws an error, if the parameter 'value' is not a number. The thrown error message must
 * be 'Parameter is not a number!'
 * @returns a new Promise, which resolves to the parameter value. returns a number after await
 */
const f = async (value) => {
  if (typeof value === 'number' && !isNaN(value)) {
    return value;
  } else {
    throw new Error("Parameter is not a number!");
  }
}

/**
 * TODO: Implement an async function 'g' that calls the previously made async function 'f'.
 * With then() function g waits for the result of f and returns the natural logarithm (Math.log()) of f's value. returns a number after await
 * Handle exceptions gracefully by returning the thrown error message with catch().
 * @param {number} value
 */
const g = async (value) => {
  try {
    const resolvedVal = await f(value);
    return Math.log(resolvedVal);
  } catch (err) {
    return err.message;
  }
}

验证效果

  • 调用await f(10)会直接返回数字10;传入非数字(比如'abc')会触发错误,被g的catch块捕获并返回错误消息。
  • 调用await g(10)会返回Math.log(10)的计算结果(约2.302),完全满足"await后返回数字"的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:00:53