如何在TypeScript中创建async函数返回fetch获取的位置坐标
解决TypeScript异步函数返回正确坐标的问题
你的问题根源是fetch是异步操作,函数在请求完成前就返回了初始定义的{ lat: 0, lng: 0 }。要让函数返回请求后的真实坐标,必须用await等待异步操作完成,确保数据获取后再返回结果。
基础实现方案
// 定义函数返回类型,符合TypeScript类型规范 async function getTargetCoordinates(location: string): Promise<{ lat: number; lng: number }> { // 替换为你的实际请求地址与参数 const response = await fetch(`https://your-api-url.com/geocode?location=${encodeURIComponent(location)}`); // 等待响应体解析为JSON const responseData = await response.json(); // 从返回数据中提取坐标(根据你的API返回结构调整) const { lat, lng } = responseData.coordinates; return { lat, lng }; }
关键说明
- 函数必须标记为
async,这是使用await的前提,同时函数会自动返回Promise类型 - 用
await分别等待fetch请求完成、响应体解析完成,确保后续代码能拿到真实数据 - 显式指定返回类型
Promise<{ lat: number; lng: number }>,让TypeScript做类型检查,避免潜在错误
带错误处理的健壮版本
实际场景中建议加入错误处理,避免请求失败或数据异常导致程序崩溃:
async function getTargetCoordinates(location: string): Promise<{ lat: number; lng: number }> { try { const response = await fetch(`https://your-api-url.com/geocode?location=${encodeURIComponent(location)}`); // 检查请求是否成功(HTTP状态码2xx) if (!response.ok) { throw new Error(`请求失败:HTTP ${response.status}`); } const responseData = await response.json(); const coordinates = responseData.coordinates; // 验证坐标是否存在且有效 if (typeof coordinates?.lat !== 'number' || typeof coordinates?.lng !== 'number') { throw new Error("API返回的坐标数据无效"); } return { lat: coordinates.lat, lng: coordinates.lng }; } catch (error) { console.error("获取坐标失败:", error); // 根据业务需求,可返回默认值或重新抛出错误 return { lat: 0, lng: 0 }; } }
内容的提问来源于stack exchange,提问作者Eshan Hirushka
相关产品推荐
相关产品推荐

