JavaScript处理GIS转GeoJSON时console.log数组长度异常问题排查
问题原因
- 异步执行顺序错误:
convertGISToGeojson是同步返回空数组,Promise.then回调属于微任务,会在当前同步代码执行完成后才触发,所以你拿到返回值的时候,数组还没被赋值。你在控制台看到数组有内容是因为控制台打印引用类型时,展示的是你点击展开时的数组最新状态,不是打印时的快照,而直接访问data[0]是取打印时的实时值,当时数组为空自然返回undefined。 - resolve时机错误:
getBuffer中shapefile.open以及后续的读取逻辑都是异步操作,你在调用完shapefile.open之后立刻resolve了空数组,此时还没有任何元素被push到geojson里,就算等promise.then执行,拿到的也只是还没填充完成的数组。
修复方案
首先调整函数逻辑,让convertGISToGeojson直接返回Promise,调用方通过await或者then获取最终结果;然后调整getBuffer的resolve时机,等所有shapefile元素读取完成后再resolve。
修复后代码
export function convertGISToGeojson(file) { if (!file) return Promise.resolve(null); return new Promise(getBuffer(file)); } function getBuffer(fileData) { return function (resolve, reject) { const reader = new FileReader(); const shapefile = require("shapefile"); reader.readAsArrayBuffer(fileData); reader.onload = async function () { try { const geojson = []; const result = reader.result; const source = await shapefile.open(result); // 循环读取所有元素 let readResult = await source.read(); while (!readResult.done) { geojson.push(readResult.value); readResult = await source.read(); } // 所有元素读取完成后再resolve resolve(geojson); } catch (error) { reject(error); } }; reader.onerror = reject; }; }
调用示例
// 方式1:async/await调用 async function handleFileUpload(file) { const geojson = await convertGISToGeojson(file); console.log(geojson[0]); // 此时可以正常访问元素 } // 方式2:then调用 convertGISToGeojson(file).then(geojson => { console.log(geojson[0]); }).catch(err => { console.error("转换失败:", err); });
内容的提问来源于stack exchange,提问作者Zenryo
相关产品推荐
相关产品推荐

