Origin Scripting Language
  • Basics
    • Syntax
    • Types
    • The Execution Loop
    • Defining Variables
      • Clone Objects (=)
      • References To Objects/Variables (@=)
    • Assignment Operators
    • Local Scoping
    • Typed Variables
  • Operators
    • Mathematical Usage
      • Addition Operator (+)
      • Subtraction Operator (-)
      • Divide Operator (/)
      • Multiply Operator (*)
      • To The Power Of (^)
      • Modulo Operator (%)
    • Text Usage
    • String Concatenation Operator (+)
    • Array Operations
    • Comparative Operators
    • Logical Operators
    • Bitwise operators
    • Pipe Operator (|>)
    • Nullish Coalescing Operator (??)
  • Program Flow
    • If Statements
      • if truthy (
      • ) else if truthy (
      • ) else (
      • )
    • Switch Case
    • Iteration
    • While And Until
    • Dynamic OSL Execution
  • Arrays And Objects
    • Making Arrays Or Objects
    • Modifying An Array
    • Clone Objects And References
    • Object Operations
    • Object Property Shorthand
  • Environment
    • The Window System
    • Mouse Cursor
    • Camera
    • Sound System
    • Input Simulation
    • Running Other Languages
    • Notifications
    • Send Data Between Windows
    • Interfacing With Rightclick
    • Permissions
    • Files
      • What is a file? (in ofsf)
      • Creating Directories
      • open("file_path")
      • fileGet(int)
      • listFiles()
  • Storage
    • Save DB
    • Local DB
  • Custom Syntax
    • Commands
    • Methods
    • Functions
    • Inline
    • Lambda
    • Spread Operator
    • Typed Parameters
    • Classes
    • Promises
  • External
    • Make An Iframe App
  • Commands
    • Debugging
      • log "hello world"
      • warn "you should change this"
      • error "something went wrong"
      • void expression
    • Rendering
      • Basics
        • Color Commands
        • Color Picker
        • Modifiers
      • Draw Cursor
        • goto x y
        • set_x x
        • set_y y
        • change_x x
        • change_y y
        • change x y
        • loc a b c d
      • Elements
        • Canvas
        • Rectangle
        • Triangle
        • Icon
        • Text
        • Image
        • Input
        • Pen
        • Hitbox
        • Bar
        • Slider
      • ICN (Icon System)
        • Drawing Commands
        • Dynamic Icons
      • Clipping And Scrolling (frames)
      • 3D Rendering
  • Functions
    • Math
      • Math()
      • random(low,high)
      • min(num1,num2)
      • max(num1,num2)
      • lcm(num1,num2)
      • gcd(num1,num2)
      • sum(num1,..)
      • average(num1,..)
      • dist(x1,y1,x2,y2)
      • degtorad(angle)
      • radtodeg(angle)
      • noise(x, y, z)
      • octaveNoise(x, y, z, octaves, persistence)
    • Types
      • typeof(value)
      • symbol(name)
    • Encoding
      • encodeURIComponent(string)
      • decodeURIComponent(string)
      • btoa/atob(string)
    • function()
    • formatFileSize(bytes)
    • getGamepads()
    • import(path)
    • ouidNew()
    • parseFilePath(path)
  • Global Variables
    • Overview
    • System Information
    • User Information
    • Date and Time
    • Input State
    • Display and UI
    • Network
    • File System
  • Methods
    • Strings
      • .padStart(num,val)
      • .padEnd(num,val)
      • .startsWith(val)
      • .endsWith(val)
      • .wrapText(characters)
      • .trimText(characters)
      • .split(characters)
      • .count(val)
      • .replace(old,new)
      • .replaceFirst(old,new)
      • .oslTokenise()
      • .strip()
      • .toOrdArray()
      • .match(pattern)
      • Encoding
        • .encodeBin()
        • .decodeBin()
        • .encodeHex()
        • .decodeHex()
        • .encodeUTF16()
        • .decodeUTF16()
        • .encrypt(password)
        • .decrypt(password)
        • .ord()
        • .chr()
      • Hashing
        • .hashMD5()
        • .hashSHA1()
        • .hashSHA256()
        • .hashSHA512()
      • Case
        • .toLower()
        • .toUpper()
        • .toMixed()
        • .toTitle()
    • Keyboard
      • .isKeyDown()
      • .onKeyDown()
    • Utilities
      • .len
      • .not
      • .ask()
      • .reverse()
      • .first()
      • .last()
      • .append(val)
      • .prepend(val)
      • .insert(location,val)
      • .delete(location)
      • .concat(val)
      • .trim(idx1,idx2)
      • .left(num)
      • .right(num)
      • .contains(val)
      • .index(val)
    • Maths
      • .abs()
      • .invabs()
      • .log()
      • .ln()
      • .isPrime()
      • .sqrt()
      • .sign()
      • .chance()
      • .clamp(low,high)
      • .toBase(base)
      • Rounding
        • .round(places)
        • .ceiling()
        • .floor()
      • Trigonometry
        • .sin
        • .cos
        • .tan
        • .asin()
        • .acos()
        • .atan()
        • .radSin()
        • .radCos()
    • Iframes
      • .iframeNew()
      • .iframeGoto()
      • .iframeResize()
      • .iframeRedirect()
      • .iframeShow()
      • .iframeHide()
      • .iframeClose()
    • JSON
      • Arrays
        • .pop()
        • .shift()
        • .randomOf()
        • .sort(direction)
        • .sortBy(key,direction)
        • .swap(idx1,idx2)
        • .fill(value)
        • .join(characters)
        • .map(callback)
        • .filter(callback)
        • .some(callback)
        • .every(callback)
      • Objects
        • .getKeys(keys)
        • .getValues()
      • .JsonStringify()
      • .JsonParse()
      • .JsonFormat()
      • .JsonClean()
    • Types
      • .getType()
      • .isType(type)
      • .toNum()
      • .toBool()
      • .toStr()
    • Functions
      • .bind(context)
    • Networking
      • .httpGet()
      • .http(method,data,headers)
      • .getAsync()
      • .roturConnect()
      • .roturSend(msg,target)
      • Websockets
        • .newWebsocket()
        • .wsSend(msg)
        • .wsClose()
        • .wsOpen()
        • .wsHasnew()
        • .wsGetnext()
        • .wsGetcount()
    • Timestamp
      • .timestamp("convert-date")
      • .timestamp("component")
Powered by GitBook
On this page
  • Creating Promises
  • Following Up Promises
  • Worker Variables
  • Promises and Mainloop

Was this helpful?

Edit on GitHub
  1. Custom Syntax

Promises

PreviousClassesNextMake An Iframe App

Last updated 9 days ago

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.

Creating Promises

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.

def fetch() (
  // Fetches a large text file
  response = "https://raw.githubusercontent.com/RoturTW/web/refs/heads/main/ram.web/assets/1mb.ram".httpGet()
)

Promise.new(fetch)

This works, however it can be inconvienent to have to define a function for every promise. Instead, we can define the function :

// Functionally identical to the script above.
Promise.new(def() -> (
  response = "https://raw.githubusercontent.com/RoturTW/web/refs/heads/main/ram.web/assets/1mb.ram".httpGet()
))

Following Up Promises

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.

myPromise @= Promise.new(fetch)

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.

myPromise.then(def() -> (
  // Log the fetched data only after the promise has been fulfilled.
  log response
))
// Returns 1, 2, 3
myPromise @= Promise.new(def() -> (
  log 1
))
myPromise.then(def() -> (
  log 2
))
myPromise.then(def() -> (
  log 3
))

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.

calculate @= Promise.new(def() -> (
  self.answer = 10 + 5
))

calculate.then(def() -> (
  log self.answer
))

Worker Variables

Promises automatically create several variables related to their status.

Variable
Type
Description

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.

secret @= Promise.new(def() -> (
  log alive
  log createdTime
  self.favoriteAnimal = "cat"
  self.favoriteOS = "originOS"
  return self.favoriteOS
))

log secret.worker.alive
log secret.worker.favoriteAnimal
log secret.worker.return

Promises and Mainloop

myPromise @= Promise.new(def() -> (
  return 45 / 5
))

myPromise.then(def() -> (
  log return
))

// Despite being nearly instant, a mainloop is still required to give the promise time to run it's course.
mainloop:
if myPromise.worker.alive.not() "window.close()"

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.

fetch from the internet
inline
mainloop