resolve()与onResult()传递Blob为空问题排查
问题:resolve返回值与回调接收值显示为空,但stream内部Blob有有效值
代码片段
attachGeoTIFFAsOverlayForPath方法:
attachGeoTIFFAsOverlayForPath(nameOfGeoTIFF) { if (nameOfGeoTIFF) { if (typeof nameOfGeoTIFF === 'string') { this.#wsGeoTIFFStreamer = new WSGeoTIFFStreamer(nameOfGeoTIFF); this.#wsGeoTIFFStreamer.setRequestOptionsParams(); this.#wsGeoTIFFStreamer.stream(result => { this.#msg = JSON.stringify({msg:verboseTag + 'xcx attachGeoTIFFAsOverlayForPath().', result: result.blob, result_: JSON.stringify(result), type: typeof result, }); console.log(this.#msg); }) .then(res => { this.#msg = JSON.stringify({msg:verboseTag + 'xcx attachGeoTIFFAsOverlayForPath().', result: res, type: typeof res, }); console.log(this.#msg); new GeoTIFF({ sources: [ { blob: res, overviews: ['https://openlayers.org/data/raster/no-overviews.tif.ovr'], }, ], }); }); } } }
stream方法:
stream(onResult) { return new Promise(async (resolve, reject) => { const ws = `${endPointsURLs.VUE_NEWSWM_APP_LOCAL_HOST_3000.description}${endPointsURLs.VUE_NEWSWM_APP_PATH.description}${BackendWssConstants.CONST_WS_GEOTIFF_STREAMER.description}/${this.#geoTIFFFileName}`; await fetch(ws, this.#requestOptions) .then(async response => { const b = await response.blob() console.log('xcx response: ', response) console.log('xcx Response status:', response.status); console.log('xcx Response headers:', response.headers); console.log('xcx blob: ', b) resolve(b); onResult(b); }) }); }
异常原因分析
回调参数的错误访问:
stream方法里调用onResult(b)时,传入的b是原生Blob对象,它本身没有blob属性。但你在attachGeoTIFFAsOverlayForPath的回调里试图访问result.blob,这必然得到undefined;同时JSON.stringify(result)无法序列化Blob对象,会输出{},所以日志里看起来result是空的。Promise返回值的日志误导:
stream里resolve的是有效的Blob对象,但JSON.stringify(res)同样无法处理Blob类型,打印出来的结果是{},让你误以为res是空的,但实际上res是正常的Blob,你后续传给GeoTIFF构造函数的blob: res是能正常工作的。
修复方案
- 回调里直接使用
result(即Blob对象),不要访问不存在的result.blob:this.#wsGeoTIFFStreamer.stream(result => { this.#msg = JSON.stringify({ msg:verboseTag + 'xcx attachGeoTIFFAsOverlayForPath().', resultSize: result.size, // 打印Blob的size属性验证有效性 resultType: result.type, // 打印Blob的type属性验证有效性 type: typeof result, }); console.log(this.#msg); }) - 打印Promise返回值时,不要用JSON.stringify,直接打印res或者它的具体属性:
.then(res => { console.log('有效Blob对象:', res); console.log('Blob大小:', res.size); // 正常初始化GeoTIFF new GeoTIFF({ sources: [ { blob: res, overviews: ['https://openlayers.org/data/raster/no-overviews.tif.ovr'], }, ], }); });
内容的提问来源于stack exchange,提问作者Amr
相关产品推荐
相关产品推荐

