Skip to content

Promises

Apoorv Singal edited this page Aug 31, 2020 · 1 revision

A promise represents the state on an async task. A promise can have two states, pending or resolved. A promise resolves to a value of its base type.

func main() {
    prom := (promise u8){}; // create a promise that resolves to a value of type u8

    prom.then(func (val: u8) {
        $printf("%i\n", val);
    });
    
    $printf("hehe\n");

    prom.resolve(10); // resolve the promise with value 10
    return 0;
}

The above program outputs,

hehe
10

Promise properties and methods

  • prom.pending is a bool which is true if prom hasn't resolved yet.
  • prom.resolved is a bool which is true if prom has already been resolved.
  • prom.then(callback) invokes callback when prom is resolved. It can be used multiple times and all the callbacks are invoked when prom is resolved.
  • prom.resolve(value) resolves the promise with value value. Using prom.resolve is not allowed if prom is a const promise.

Note: Using the dollar sign to access c APIs is not recommended and will be depreciated soon. See [link] for more info.

Clone this wiki locally