`async` 函数始终返回 promise,因此直接 `console.log(createquiz(...))` 只会输出 `promise { pending }`;必须通过 `.then()` 或 `await` 获取解析值,而非期望同步返回结果。
在 JavaScript 中,async 函数本质上是语法糖,它自动将返回值包装为 Promise。无论你在 try、catch 或函数末尾 return "success" 还是 return e.message,该返回值都会被隐式转换为 Promise.resolve("success") 或 Promise.reject(...)(仅当抛出未捕获异常时)。因此,调用 createQuiz(...) 永远得到一个 Promise 实例,而非字符串 "success" 或错误消息。
// 方式 1:使用 .then() 处理成功/失败(推荐用于非顶层调用)
createQuiz(questions, quizDetails)
.then(result => console.log("Result:", result)) // "success" 或错误消息
.catch(err => console.error("Unexpected rejection:", err)); // 理论上不会触发,因 catch 已处理// 方式 2:在 async 上下文中使用 await(更直观,需包裹在 async 函数中)
async function run() {
try {
const result = await createQuiz(questions, quizDetails);
console.log("Created:", result); // 直接拿到 "success" 或 e.message
} catch (err) {
// 注意:此 catch 仅捕获 createQuiz 内部未处理的异常(如未 catch 的 throw)
console.error("Unhandled error:", err);
}
}
run();return 在 async 函数内 ≠ 同步返回:它只是决定 Pro
mise 的 fulfilled 值,不改变函数的异步本质。
catch 中 return 不会抛出错误:它返回一个 fulfilled Promise(值为 e.message),因此外部 .catch() 不会触发 —— 这是设计使然,表示“错误已被处理并转化为正常响应”。
若你希望错误仍以 rejected Promise 形式向外传播(例如让调用方统一处理异常),应改用 throw e 而非 return e.message:
} catch (e) {
throw new Error(`Quiz creation failed: ${e.message}`); // 继续 reject
}总之,console.log(createQuiz(...)) 打印 Promise { pending } 是完全符合预期的行为;真正的“返回值”需通过 Promise 消费机制获取 —— 这不是 bug,而是 async/await 的核心契约。