Reputation: 30045
I'm a c++ programmer learning javascript.
I have a javascript function loadTexture to load an image from a URL and create an opengl texture from it. It works asynchronously and returns a Promise object so that I can tell when it's finished. All good :)
But I'd like to be able to tell it where to store the resulting opengl texture id, something like this -
var catImageFuture = loadTexture("cat.png", this.catTextureId);
/* Wait for the future, and several other ones to complete before doing the next thing */
And have it store the opengl id it generates in the variable I passed in as the second parameters. In C++ this would be simple, I could pass a reference or a pointer to the variable to the function. But this isn't possible in Javascript as it has no pass by reference or pointers.
What is the right way to achieve a similar aim in Javascript.
Upvotes: 3
Views: 284
Reputation: 17521
There are several ways:
You can use custom object and manage that, like:
var cat = new Cat();
cat.texture = new Texture();
...
Or you can use callbacks:
var TextureId;
function loadTexture(path, callback)
{
var img = new Image(path);
var id = (GetSomeHowId);\
img.onload = (function(i){ return (function(){callback(i);}); })(id);
}
loadTexture("cat.png", (function(id){ TextureId = id; }));
Hope you got the point.
Upvotes: 1
Reputation: 782105
In Javascript you would use a function. The function would receive the data as a parameter and store it wherever is appropriate. You might use a closure to capture a reference to a local variable.
Another option is to always wrap the data in an object. Pass the object to your function, and ithe function can assign a property of the object. Objects and arrays are passed like pointers in Javascript, so when the function modifies it, it will be visible to the caller.
Upvotes: 1
Reputation: 298432
JavaScript has no mechanism (yet) to elegantly inline asynchronous code. Right now, everything is done with callbacks. If you implement a done
method on your Future
object that passes its result as an argument to a callback, you'd be able to write:
var that = this; // You may need this, depending on how you implement Future.done
loadTexture("cat.png").done(function(result) {
that.catTextureId = result;
});
JavaScript runtimes will support generators in a few years, so you'll soon be writing:
this.catTextureId = yield loadTexture("cat.png");
Upvotes: 3