
async 函数始终返回 Promise,不能直接获取其解析后的值;必须使用 await(在 async 上下文中)或 .then()(在普通上下文中)来提取结果。
`async` 函数始终返回 promise,不能直接获取其解析后的值;必须使用 `await`(在 async 上下文中)或 `.then()`(在普通上下文中)来提取结果。
在构建基于 Google Cloud Translation API 的翻译应用时,一个常见误区是误以为 async 函数会“同步返回”最终数据。例如,以下代码看似直观:
const apiTranslate = (() => {
const _API_KEY = "your-api-key";
async function getTranslation(text) {
const res = await axios.post(
`https://translation.googleapis.com/language/translate/v2?key=${_API_KEY}`,
{ q: text, target: "de" }
);
const translation = res.data.data.translations[0].translatedText;
console.log(translation); // ✅ 正确输出:Hello Welt
return translation; // ⚠️ 但这里返回的是 Promise,不是字符串!
}
return { getTranslation };
})();
const { getTranslation } = apiTranslate;
const message = getTranslation("hello world");
console.log(message); // ❌ 输出:Promise {<pending>}</pending>
原因在于:所有 async 函数隐式返回 Promise —— 即使你 return "Hello Welt",实际返回的是 Promise.resolve("Hello Welt")。因此,message 是一个待决 Promise,而非翻译文本本身。
通过 SerpApi 查询 Google Flights,获取航班时刻表、价格及舱位等级信息。当用户询问航班 / 机票 / 航班价格、时刻表或对比信息时使用。
✅ 正确用法一:使用 .then()(适用于普通脚本环境)
getTranslation("hello world")
.then(translation => {
console.log(translation); // ✅ 正确输出:Hello Welt
// 在此处进行后续操作(如更新 DOM、存入状态等)
})
.catch(err => console.error("翻译失败:", err));
✅ 正确用法二:使用 await(需在 async 函数内)
const translateAndLog = async () => {
try {
const { getTranslation } = apiTranslate;
const message = await getTranslation("hello world");
console.log(message); // ✅ Hello Welt
return message;
} catch (err) {
console.error("请求异常:", err.response?.statusText || err.message);
}
};
translateAndLog(); // 调用该 async 函数
✅ 正确用法三:立即执行的异步函数(IIFE)
(async () => {
const { getTranslation } = apiTranslate;
try {
const message = await getTranslation("hello world");
console.log(message); // ✅ Hello Welt
} catch (err) {
console.error(err);
}
})();
⚠️ 注意事项
-
不可在顶层作用域直接
await(ES2017+ 模块支持顶层 await,但需明确设置type="module"):若在<script></script>标签中运行,推荐使用 IIFE 或封装为函数。 -
务必添加错误处理:网络请求可能失败(如密钥无效、配额超限、跨域限制),应始终包裹
try/catch或.catch()。 -
避免“忘记 await”的陷阱:
const msg = getTranslation(...)不会报错,但msg是 Promise —— 后续若误当字符串使用(如msg.toUpperCase()),将触发TypeError。
掌握 Promise 与 async/await 的本质关系,是构建健壮前端 API 集成的关键一步。记住:调用 async 函数 ≠ 获取最终值;它只是启动异步任务并返回控制权。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










