含Await Fetch的Async函数执行完成后需返回自定义值问题
解决async函数返回指定字符串的问题
问题分析
你编写的uspsVerification是async函数,需要返回"success"或"failure"字符串,但当前写法存在两个核心问题:
问题1:函数返回Promise<void>而非期望的Promise<string>
原代码中,await fetch(...)的链式调用里,then回调返回的"success"/"failure"没有被外层函数return,导致整个uspsVerification函数无返回值,TypeScript推断其类型为Promise<void>。此外,调用时直接拿result和字符串比较,忽略了async函数返回的是Promise,必须通过await或.then()获取实际值。
问题2:手动包裹new Promise导致await报错
async函数本身会自动将返回值包装为Promise,无需手动创建新Promise。你在new Promise的普通回调函数里使用await,但该回调不是async函数,因此触发"await仅允许在async函数或模块顶层使用"的错误。
正确写法
推荐用async/await替代then链式调用,代码更直观易维护:
const uspsVerification = async (addr: string) => { //... 额外逻辑 ... // 用await替代then链 const res = await fetch("/service/verify-address", requestOptions); const data = await res.json(); // ... 额外逻辑 ... // 直接返回字符串,async函数会自动包装为Promise<string> if (someCondition1) { return "success"; } else { return "failure"; } }
如果一定要保留then链式调用,需要把then链的结果return出去:
const uspsVerification = async (addr: string) => { //... 额外逻辑 ... // return then链的结果,确保函数返回Promise<string> return await fetch("/service/verify-address", requestOptions) .then(res => res.json()) .then(data => { // ... 额外逻辑 ... if (someCondition1) { return "success"; } else { return "failure"; } }); }
正确调用方式
由于async函数返回的是Promise,不能直接拿返回值和字符串比较,必须用以下两种方式:
方式1:在async函数内用await
async function handleAddrVerification() { const result = await uspsVerification("测试地址"); if (result === "success") { // 执行成功逻辑 } else { // 执行失败逻辑 } }
方式2:用.then()处理结果
uspsVerification("测试地址").then(result => { if (result === "success") { // 执行成功逻辑 } else { // 执行失败逻辑 } });
内容的提问来源于stack exchange,提问作者gene b.
相关产品推荐
相关产品推荐

