Promises
Last updated
Was this helpful?
Last updated
Was this helpful?
By default, OSL scripts will run synchronously. This means that every line runs one after another in a sequence. However, this also means if one especially resource intensive command takes a while to run, the rest of the code will have to wait until after it's finished to execute. A similar issue occurs when trying to , which will almost always need the extra time to run.
Sometimes, it can be helpful to run a script asynchronously (also referred to as async). Promises provide an easy way to do just that.
To create a promise, we can use the Promise object with the method "new". This method takes one parameter, which is the function to be run async.
This works, however it can be inconvienent to have to define a function for every promise. Instead, we can define the function :
We can now create asynchronous scripts, however the data they provide isn't very useful to us in this state. Remember, these scripts run completely independently from the rest of the program; as such, it's difficult to know exactly when a promise is wrapped up. Luckily, there's another method we can use to help. To access it though, we'll need a reference to the promise we just created.
Using this reference, we can call on the "then" method to run a follow-up script after the initial promise has concluded. Similarly to the prior method, this one takes only a function as the parameter. There's no limit to the amount of "then" statements that can be added to one promise; in the case that there are multiple, they will run in the order they were defined.
Oftentimes, it'll be important to transfer variables from the initial promise to the follow-up function. We can do this with global variables (such as in the above examples), but a much cleaner way to accomplish this would be to store it in the promise itself using the "self" object.
Promises automatically create several variables related to their status.
alive
Boolean
Returns false if the promise has concluded, otherwise return true.
createdTime
Number
The timestamp at which the promise was first created.
processTime
Number
How long it took to run the promise, in seconds.
return
Any
If the previous function in a promise had a return value, return that. Otherwise, return null. For use outside of the promise, only look for a return command in the last function of that promise.
Any of these variables can also be accessed outside their respective promise by accessing the "worker" property in the referenced promise. Additionally, any variables created with the "self" object will appear here too, minus the "self" prefix.
Another important thing to note about promises is that the main script will not wait for them to finish before ending the entire program. As such, promises may not work as expected without a in the project, as most promises will not be able to conclude in one frame before the program automatically shuts down.