简体   繁体   中英

Export Object after promise is resolved

I am using "load" and "OBJloader" from loaders.gl/core and loaders.gl/obj to load a mesh to export it as a const so other module can use it, currently I am using this

export const myMesh = Object.freez({
     mesh : load(path_to_obj_file,OBJLoader),
     origin: [1.4,0,2.2],
     dimensions: [2,2,2],
     scale: 1
)}

but then I find out that I can calculate the origin and dimensions from the obj file itself without the need to put them manually (I used to calculate them form meshlab), and I can do it from the load function itself

load(path_to_obj_file,OBJLoader).then((obj)=>{
console.log(obj.schema.metadata.get["boundingBox"]
}

boundingBox would be like that [[-1.4,-1,-2],[0.6,1,-0.2]] (numbers are not accurate at all). and I can calculate origin and dims from the boundingBox.

my question is, how can I export the const myMesh now? since I have promise, also when we write:

mesh : load(path_to_obj_file,OBJLoader) 

could that cause a problem since load returns a promise? (currently it is working correctly)

I tried:

export const loadMyMesh = load(path_to_obje_file,OBJLoader).then((obj) =>{
     const myMesh = Object.freez({
     mesh: obj,
     origin: calculateOrigin(obj),
     dimensions: claculateDim(obj),
     scale: 1
    });
  return myMesh
})

where calculateOrigin and calculateDim are functions used to get the boundingbox and calculate the origin and the dims, but that didn't work.

so any solution?

In mesh: obj , the value is supposed to be a Promise, so if the promise is used as a synchronization flag, it can be a problem. But generally, a promise that produces a certain value, and the value itself are equivalent when await ed. As in, 2 == await 2 .

One solution is to do const myMesh = await loadmyMesh; in other modules.

Another solution is a little more complicated, but this way, you don't have to change anything in the other modules. Just beware that myMesh is not frozen until the calculations are done.

export const myMesh = {
    scale: 1
};

myMesh.mesh = load(path_to_obj_file, OBJLoader).then(obj => {
    myMesh.origin = calculateOrigin(obj);
    myMesh.dimensions = claculateDim(obj);
    Object.freeze(myMesh);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM