# Worker functions

Source: https://zotonic.com/cotonic/worker_functions

URI: https://zotonic.com/id/2732

Language: en



<a name="worker.functions"></a>
Workers are stand alone processes. They have no shared data with the page, nor with other workers. Their memory and calling context is isolated. They can easily communicate with other workers, the page, and servers by publising messages on topics, and subscribing to them. Cotonic provides [models](/id/doc_cotonic_models#models), modules which are loaded and ready for requests.
<!-- worker init--> <a name="worker.on_init"></a>
on\_init `self.on_init(arguments)`
----------------------------------

The callback <tt>on_init</tt> is called when the worker receives the initialization message by the page. It can take multiple arguments. The arguments are passed in via the [<tt>spawn</tt>](/id/doc_cotonic_functions#cotonic.spawn) <tt>args</tt> argument list. This function can be used to initialize the worker. The callback is optional.

```
// Page code.
cotonic.spawn("example_worker", [amount, target]);

// Worker code

let amount = null;
let targetId = null;

self.on_init = function(n, id) {
    amount = n;
    targetId = id;
}
==> Worker receives the arguments which can be used for initialization.
```
<!-- worker connect --> <a name="worker.connect"></a>
connect `self.connect(connectOptions)`
--------------------------------------

Connect the worker to the page. Returns a promise. This promise is resolved when the worker is connected to the page. When is indicated in the <tt>connectOptions</tt> that the worker depends on other services the promise is resolved after those dependencies have become available. Parameter <tt>connectOptions</tt> supports the following options:

<dl>
                <dt><tt>name</tt></dt>
                <dd>The name of the worker.</dd>

                <dt><tt>depends</tt></dt>
                <dd>A list of dependencies on which the worker needs. The connect promise will be
                resolved, after the dependencies become available.</dd>

                <dt><tt>provides</tt></dt>
                <dd>A list of dependencies which is provided by this worker. The are published after
                the worker is connected.</dd>
            </dl>

```
self.connect().then(
    function() {
        console.log("Connected");
    }
);
=> The worker is being connected to the page.
```

```
self.connect({depends: ["model/ui",
                        "model/serviceWorker",
                        "worker/abc"]}).then(
    function() {
        console.log("Connected, the requested dependencies are available, and worker abc is started.");
    }
);
=> The worker is being connected to the page, and the requested dependencies are available.
```
<!-- worker disconnect --> <a name="worker.disconnect"></a>
disconnect `self.disconnect()`
------------------------------

Disconnects the worker from the page. After this step it is no longer possible to send and receive messages from the page.

```
self.disconnect();
=> The worker is disconnected from the page.
```
<!-- worker is_connected --> <a name="worker.is_connected"></a>
is\_connected `self.is_connected()`
-----------------------------------

Returns <tt>true</tt> iff the worker is connected to the page, <tt>false</tt> otherwise.

```
self.is_connected();
=> true
```
<!-- worker whenDependencyProvided --> <a name="worker.whenDependencyProvided"></a>
whenDependencyProvided `self.whenDependencyProvided(dependency)`
----------------------------------------------------------------

Returns a Promise which is resolved when the external dependency is provided.

```
self.whenDependencyProvided("model/ui").then(
    function() {
        worker.publish("model/ui/insert/foo", {..});
    });
```
<!-- worker whenDependenciesProvided --> <a name="worker.whenDependenciesProvided"></a>
whenDependenciesProvided `self.whenDependenciesProvided(dependencies)`
----------------------------------------------------------------------

Returns a Promise which is resolved when all external dependencies are provided.

```
self.whenDependenciesProvided(["model/ui", "model/x"]).then(
    function() {
        ...
    });
==> The promise will be resolved after the ui and x model are provided.
```
<!-- worker provides --> <a name="worker.provides"></a>
provides `self.provides(modelsAndWorkers)`
------------------------------------------

Indicate to other workers and the page that this worker provides models or workers. Other workers waiting on these dependencies will get notified when they become available. The parameter <tt>modelsAndWorkers</tt> should be a list with model or worker names this worker provides.

```
self.provides(["model/a", "model/b", "worker/x"])
==> When the worker connects, it will notify other workers that new models
    have become available.
```
<!-- worker subscribe --> <a name="worker.subscribe"></a>
subscribe `self.subscribe(topics, callback, ack_callback)`
----------------------------------------------------------

Subscribe the worker to the <tt>topics</tt>. When a message is received, the <tt>callback</tt> is called. Callback is a function which receives two parameters. The first parameter is the <tt>message</tt>, the second parameter an <tt>object</tt> returned by [extract](/id/doc_cotonic_cotonic_mqtt#cotonic.mqtt.extract). This can be used to easily extract elements from topic paths in an object. The parameter <tt>topics</tt> can be a string, or a list of strings. The callback <tt>ack_callback</tt> is used when the page is subscribed, or when there is a problem. Returns nothing.

```
function logSpeed(msg, args) {
    if(args.boat_id) {
        console.log("boat", args.boat_id, "is now moving at", msg.payload);
    }
    if(args.truck_id) {
        console.log("truck", args.truck_id, "is now moving at", msg.payload);
    }
}
self.subscribe(["truck/+boat_id/speed", "boat/+boat_id/speed"], logSpeed);
=> The function logSpeed will be called when somebody sends a message which
   matches the topics.
```
<!-- worker unsubscribe --> <a name="worker.unsubscribe"></a>
unsubscribe `self.unsubscribe(topics, callback, ack_callback)`
--------------------------------------------------------------

Unsubscribe the worker from page. The worker will no longer receive messages from the specified topics.

```
self.unsubscribe();
```
<!-- worker publish --> <a name="worker.publish"></a>
publish `self.publish(topic, message, options)`
-----------------------------------------------

Publish <tt>message</tt> on <tt>topic</tt>. The <tt>options</tt> can be used to indicate the quality of service, or if the message should be retained by the broker.

```
self.publish("world", "hello", {retain: true});
```
<!-- worker call --> <a name="worker.call"></a>
call `self.call(topic, message, options)`
-----------------------------------------

Publishes <tt>message</tt> on <tt>topic</tt> and subscribes itself to a reply topic. Returns a promise which is fulfilled when a message is received on the reply topic. When no message arrives, the promise is rejected. Returns a promise.

```
self.call("model/document/get/all")
.then(...)
.reject(...);
```

License: 

Attribution: 

Related resources: https://zotonic.com/api/agent/related/2732?language=en


## API access

- [API help](<https://zotonic.com/api-help>)
- [OpenAPI specification](<https://zotonic.com/openapi.json>)
- [This resource as JSON](<https://zotonic.com/api/agent/resource/2732?language=en>)
