一旦所有网址都提取并添加到对象mapGeometry中,我将使用下面的异步代码来获取网址数组。我需要从returnMapGeometry函数返回mapGeometry,因此所有代码都需要暂停直到执行。
我在正确设置语法上遇到了很多麻烦,一旦所有获取都解决了并且每个mapGeometryPiece已添加到mapGeometry中,如何返回mapGeometry?
function returnMapGeometry() {
var mapGeometry = new THREE.Group();
Promise.all(
urls.map((url, index) => fetch(new Request(url))
.then(response => response.blob())
.then(blob => doSomeWork(URL.createObjectURL(blob))
.then(mapGeometryPiece => {
mapGeometry.add(mapGeometryPiece)
})
))
}
// code must pause until returnMapGeometry() returns
mapGeometry = returnMapGeometry()
注意:mapGeometry是Three.js组-我认为这没有什么区别,请参阅:https://threejs.org/docs/#api/objects/Group
答案 0 :(得分:3)
您需要在.then
上链接并返回一个Promise.all
,以您所构造的mapGeometry
进行解析,然后在调用returnMapGeometry
时,它将解析mapGeometry
。因为它需要返回一个Promise
而不是实际的mapGeometry
,所以更有意义的是调用该函数,例如getMapGeometry
。
您还可以删除.then
上不必要的嵌套doSomeWork
,以使代码更扁平:
function getMapGeometry() {
var mapGeometry = new THREE.Group();
return Promise.all(
urls.map((url, index) => fetch(new Request(url))
.then(response => response.blob())
.then(blob => doSomeWork(URL.createObjectURL(blob))
.then(mapGeometryPiece => mapGeometry.add(mapGeometryPiece))
))
)
.then(() => mapGeometry);
// code must pause until returnMapGeometry() returns
}
getMapGeometry()
.then((mapGeometry) => {
// do stuff with mapGeometry
});