JavaScript中使用Promise调用API返回undefined问题求助
解决Promise返回undefined的问题
你的代码输出Promise { undefined }的核心原因是**getClosestSchachtInSeg函数没有返回任何异步操作的结果**,同时内部异步流程未正确处理。以下是具体问题分析和修正方案:
问题分析
getClosestSchachtInSeg被声明为async函数,但函数体内无return语句,默认返回Promise{undefined}- 内部
pool.query()和fetch()等异步操作使用.then()链式调用,但未将结果传递出函数 - 循环中的
fetch未被等待,也未收集返回值,导致异步结果丢失
修正后的代码
第一步:修复getClosestSchachtInSeg函数
改用async/await简化异步流程,确保函数返回最终结果:
async function getClosestSchachtInSeg( LON, LAT, FROMANGLE, TOANGLE, NS, maxCount ) { try { const sqlQuery = "SELECT *, ST_X(ST_Transform (geom, 4326)) AS LON, ST_Y(ST_Transform (geom, 4326)) AS LAT," + " ST_Transform(SCHAECHTE_OWN.geom, 4326) <-> ST_SetSRID(ST_MakePoint(" + LON + ", " + LAT + "), 4326)::geometry AS dist " + ' FROM public."SCHAECHTE_OWN" SCHAECHTE_OWN ' + " WHERE atan((ST_X(ST_Transform (geom, 4326)) - " + LON + ") / (ST_Y(ST_Transform (geom, 4326)) - " + LAT + ") > " + FROMANGLE + "*pi()/180" + " AND atan((ST_X(ST_Transform (geom, 4326)) - " + LON + ") / (ST_Y(ST_Transform (geom, 4326)) - " + LAT + ") < " + TOANGLE + "*pi()/180" + " AND ST_Y(ST_Transform (geom, 4326)) " + NS + " " + LAT + " ORDER BY dist LIMIT " + maxCount + ";"; // 等待SQL查询结果 const results = await pool.query(sqlQuery); const resultList = []; if (results.rows.length > 0) { // 用map+Promise.all处理多个fetch请求 const fetchPromises = results.rows.map(async (row) => { const ResLon = row.lon; const ResLat = row.lat; const ResDist = row.dist; const urlDistance = "http://gisdatavm01hw.versatel.local:5001/getShortestPathLonLatDistance/" + Math.round(LON * 1000000) / 1000000 + "/" + Math.round(LAT * 1000000) / 1000000 + "/" + Math.round(ResLon * 1000000) / 1000000 + "/" + Math.round(ResLat * 1000000) / 1000000; const response = await fetch(urlDistance); const body = await response.text(); const Dist = JSON.parse(body)["distance"]; // 返回包含目标浮点数的对象,可根据需求调整结构 return { lon: ResLon, lat: ResLat, dist: ResDist, pathDistance: Dist || null }; }); // 等待所有fetch完成,收集结果 const fetchedResults = await Promise.all(fetchPromises); resultList.push(...fetchedResults); } // 返回最终结果,使函数返回带数据的Promise return resultList; } catch (err) { console.error("Error executing query", err.stack); throw err; // 抛出错误供调用方捕获 } }
第二步:修复getClosestSchachtOWNJson12SegNew函数
使用Promise.all()等待所有异步调用完成,替代Promise.resolve():
async function getClosestSchachtOWNJson12SegNew(request, response) { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader( "Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT" ); response.setHeader( "Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers" ); const LON = request.params.LON; const LAT = request.params.LAT; const maxCount = request.params.maxCount; // 等待所有12个异步函数执行完成 const values = await Promise.all([ getClosestSchachtInSeg(LON, LAT, -90, -60, ">=", maxCount), getClosestSchachtInSeg(LON, LAT, -60, -30, ">=", maxCount), getClosestSchachtInSeg(LON, LAT, -30, 0, ">=", maxCount), getClosestSchachtInSeg(LON, LAT, 0, 30, ">=", maxCount), getClosestSchachtInSeg(LON, LAT, 30, 60, ">=", maxCount), getClosestSchachtInSeg(LON, LAT, 60, 90, ">=", maxCount), getClosestSchachtInSeg(LON, LAT, -90, -60, "<", maxCount), getClosestSchachtInSeg(LON, LAT, -60, -30, "<", maxCount), getClosestSchachtInSeg(LON, LAT, -30, 0, "<", maxCount), getClosestSchachtInSeg(LON, LAT, 0, 30, "<", maxCount), getClosestSchachtInSeg(LON, LAT, 30, 60, "<", maxCount), getClosestSchachtInSeg(LON, LAT, 60, 90, "<", maxCount), ]); console.log(values); // 如需返回给前端,可添加:response.json(values); }
关键修正点
- 给
getClosestSchachtInSeg添加return语句,传递异步操作结果 - 用
await替代.then(),简化异步流程可读性 - 用
Promise.all()处理循环中的多个fetch,确保所有异步操作完成后返回 - 在主函数中用
Promise.all()等待所有子函数调用完成,而非直接包裹数组
内容的提问来源于stack exchange,提问作者CodeoDE
相关产品推荐
相关产品推荐

