---
title: "Operations"
url: https://docs.zeroc.com/ice/3.8/slice/operations
language: js
docs_index: https://docs.zeroc.com/llms.txt
---

> For an index of every page, see [llms.txt](https://docs.zeroc.com/llms.txt).

# Operations

Programming language: JavaScript. Other languages: [C++](https://docs.zeroc.com/ice/3.8/slice/operations/cpp.md), [C#](https://docs.zeroc.com/ice/3.8/slice/operations/csharp.md), [Java](https://docs.zeroc.com/ice/3.8/slice/operations/java.md), [MATLAB](https://docs.zeroc.com/ice/3.8/slice/operations/matlab.md), [PHP](https://docs.zeroc.com/ice/3.8/slice/operations/php.md), [Python](https://docs.zeroc.com/ice/3.8/slice/operations/python.md), [Ruby](https://docs.zeroc.com/ice/3.8/slice/operations/ruby.md), [Swift](https://docs.zeroc.com/ice/3.8/slice/operations/swift.md).

## Operation Syntax

An operation definition has a name, a return type, and zero or more parameters.

For example:

```slice
module M
{
    struct TimeOfDay
    {
        short hour;         // 0 - 23
        short minute;       // 0 - 59
        short second;       // 0 - 59
    }

    interface Clock
    {
        TimeOfDay getTime();
        void setTime(TimeOfDay time);
    }
}
```

An operation that returns no value, such as `setTime`, declares `void` as its return type.

Parameters are input parameters by default: their values go from the client to the server. An output parameter, marked with the `out` keyword, carries a value from the server back to the client. An operation can have several input and output parameters, and its output parameters must follow its input parameters:

```slice
module M
{
    interface CircadianRhythm
    {
        void setSleepPeriod(TimeOfDay startTime, TimeOfDay stopTime);
        void getSleepPeriod(out TimeOfDay startTime, out TimeOfDay stopTime);
        void changeSleepPeriod(
            TimeOfDay startTime,
            TimeOfDay stopTime,
            out TimeOfDay prevStartTime,
            out TimeOfDay prevStopTime);
    }
}
```

Each parameter must have a name, and a parameter cannot be both an input and an output parameter.

## Optional Parameters and Return Values

An operation's return value and parameters may be declared as optional to indicate that a program can leave their values unset. Parameters not declared as optional are known as *required* parameters. In the discussion below, we use *parameter* to refer to input parameters, output parameters, and return values.

A unique, non-negative integer *tag* must be assigned to each optional parameter:

```slice
optional(3) bool example(optional(2) string name, out optional(1) int value);
```

The scope of a tag is limited to its operation and has no effect on other operations. You can assign tags in any order.

An optional parameter cannot have a class type, or a constructed type that holds a class type.

An operation's signature can include any combination of required and optional parameters, but output parameters still must follow input parameters:

```slice
bool example(
    string name,
    optional(3) string referrer,
    out optional(1) string promo,
    out int id);
```

Language mappings specify an API for passing optional parameters and testing whether a parameter is present.

## Exception Specifications

An operation lists the user exceptions it can throw in its [exception specification](https://docs.zeroc.com/ice/3.8/slice/exceptions/js.md#exception-specification-in-operations), a `throws` clause.

## Overloading Operations

Slice does not support overloading: operations in the same interface must have different names, regardless of the type and number of their parameters. A request identifies the operation it invokes by name only.

## Idempotent Operations

An operation is idempotent when calling it several times with the same arguments has the same effect as calling it once. Operations that do not modify the state of the object, such as `getTime` in the `Clock` interface, are idempotent; so is `setTime`, even though it modifies the state. You mark such operations with the `idempotent` keyword:

```slice
interface Clock
{
    idempotent TimeOfDay getTime();
    idempotent void setTime(TimeOfDay time);
}
```

The `idempotent` keyword makes this property part of the contract: the implementation must keep the operation idempotent, and callers can rely on it. Ice relies on it to retry invocations it would not retry otherwise; see [Automatic Retries](https://docs.zeroc.com/ice/3.8/runtime/invocation/automatic-retries/js.md).

## Client-Side Mapping for Operations

### Mapping for Operations

For each Slice operation defined on an interface, the generated proxy class provides a method with the same name. To invoke an operation, you call this method on the proxy.

For example, consider the following Slice definition:

```slice
module VisitorCenter
{
    interface Greeter
    {
        string greet(string name);
    }
}
```

The generated proxy class (simplified) looks like this:

```js
class GreeterPrx extends Ice.ObjectPrx {
    constructor(communicator, proxyString) { ... }

    greet(name, context) { ... }

    // ...
}
```

And the TypeScript declaration:

```typescript
export namespace VisitorCenter {
    export class GreeterPrx extends Ice.ObjectPrx {
        constructor(communicator: Ice.Communicator, proxyString: string);

        greet(name: string, context?: Map<string, string>): Ice.AsyncResult<string>;

        // ...
    }
}
```

> **Note**
>
> `Ice.AsyncResult` extends the JavaScript `Promise` type. It adds functionality specific to Ice invocations.

Given a proxy to a Greeter object, a client can invoke greet as follows:

```typescript
const greeter = new VisitorCenter.GreeterPrx(
    communicator,
    "greeter:tcp -h localhost -p 4061");

const greeting = await greeter.greet("Alice");  // Get name via RPC
```

Ice for JavaScript supports only **asynchronous method invocation (AMI)**. The JavaScript runtime does not provide a blocking I/O model in order to keep the event loop responsive.

The value that fulfills the promise depends on the number of results, counting the return value and the out parameters:

- With **no results**, Ice fulfills the promise with `undefined`.
- With **one result**, either the return value or a single out parameter, Ice fulfills the promise with that value.
- With **several results**, Ice fulfills the promise with an array: the return value (if any) followed by the out parameters in declaration order.

The mapping uses an array so that you can bind the results with a destructuring assignment. The proxy method declares this array as a TypeScript tuple, so each variable gets the type of its result. For example, given the following operation:

```slice
string getTime(out int hour, out int minute);
```

A client retrieves the three results as follows:

```typescript
const [time, hour, minute] = await clock.getTime();
```

### Exception Handling

Any operation invocation may throw a [local exception](https://docs.zeroc.com/ice/3.8/runtime/local-and-dispatch-exceptions/js.md) and, if the operation has an exception specification, may also throw [user exceptions](https://docs.zeroc.com/ice/3.8/slice/exceptions/js.md). Suppose we have the following simple interface:

```slice
exception Tantrum
{
    string reason;
}

interface Child
{
    void askToCleanUp() throws Tantrum;
}
```

Slice exceptions are thrown as JavaScript exceptions, so you can simply enclose one or more operation invocations in a try-catch block:

```typescript
const child = ...   // Get child proxy...

try {
    await child.askToCleanUp();
} catch (error: unknown) {
    if (error instanceof Tantrum) {
        console.log("The child says:", error.reason);
    } else {
        throw error;
    }
}
```

## Server-Side Mapping for Operations

For each Slice operation defined on an interface, the generated skeleton class includes a corresponding abstract member function with the same name.

For example, consider the following Slice definition:

```slice
module VisitorCenter
{
    interface Greeter
    {
        string greet(string name);
    }
}
```

The generated JavaScript skeleton class is:

```js
VisitorCenter.Greeter = class extends Ice.Object {};
```

Since JavaScript does not support abstract methods, the generated class does not provide an actual abstract declaration. Instead, the servant class that derives from this skeleton must add the operation implementations, as if the methods were abstract.

This is clearer in the generated TypeScript declarations, which can use abstract methods:

```typescript
export abstract class Greeter extends Ice.Object {
    abstract greet(
        name: string,
        current: Ice.Current): PromiseLike<string> | string;
    // ...
```

The servant implementation can choose how to provide the result:

- **Return the result directly** (synchronous implementation).
- **Return a promise-like object** that will be fulfilled with the result.
- **Declare the method as async** and use await inside the implementation.

A servant method provides its results by the same rule as the client side, such as `return [time, hour, minute];` for the `getTime` operation above.

**Synchronous version:**

```typescript
greet(name: string, current: Ice.Current): PromiseLike<string> | string {
    return `Hello, ${name}`;
}
```

**Asynchronous version:**

```typescript
async greet(name: string, current: Ice.Current): Promise<string> {
    // Nested async invocation
    return await this._target.greet(name);
}
```

## Mapping for Parameters and Return Values

### Passing Parameters in JavaScript

The parameter passing rules for the JavaScript mapping are very simple: parameters are passed either by value (for simple types) or by reference (for complex types). Semantically, the two ways of passing parameters are identical: it is guaranteed that the value of a parameter will not be changed by the invocation. A `long` parameter also accepts a `number`, as described in [Basic Types](https://docs.zeroc.com/ice/3.8/slice/basic-types/js.md).

Here is an interface with operations that pass parameters of various types from client to server:

```slice
struct NumberAndString
{
    int x;
    string str;
}

sequence<string> StringSeq;

dictionary<long, StringSeq> StringTable;

interface ClientToServer
{
    void op1(int i, float f, bool b, string s);
    void op2(NumberAndString ns, StringSeq ss, StringTable st);
    void op3(ClientToServer* proxy);
}
```

The Slice compiler generates the following proxy methods for these definitions:

```js
class ClientToServerPrx extends Ice.ObjectPrx {
    op1(i, f, b, s, context) { ... }
    op2(ns, ss, st, context) { ... }
    op3(proxy, context) { ... }
}
```

```typescript
class ClientToServerPrx extends Ice.ObjectPrx {
    op1(
        i:number,
        f:number,
        b:boolean,
        s:string,
        context?:Map<string, string>):Ice.AsyncResult<void>;

    op2(
        ns:NumberAndString,
        ss:string[],
        st:Map<bigint, string[]>,
        context?:Map<string, string>):Ice.AsyncResult<void>;

    op3(
        proxy:ClientToServerPrx | null,
        context?:Map<string, string>):Ice.AsyncResult<void>;
}
```

Given a proxy to a `ClientToServer` interface, the client code can pass parameters as in the following example:

```js
const p = ...;          // Get ClientToServerPrx proxy...

await p.op1(42, 3.14, true, "Hello world!");  // Pass simple literals

const i = 42;
const f = 3.14;
const b = true;
const s = "Hello world!";
await p.op1(i, f, b, s);                      // Pass simple variables

const ns = new NumberAndString();
ns.x = 42;
ns.str = "The Answer";
const ss = [];
ss.push("Hello world!");
const st = new StringTable();
st.set(0n, ss);
await p.op2(ns, ss, st);                      // Pass complex variables

await p.op3(p);                               // Pass proxy
```

### Null Parameters in JavaScript

Slice strings, sequences, and dictionaries have no null value. When you pass `null` or `undefined` for one of these types, whether as a parameter, a return value, a field, or a sequence element, Ice sends an empty string, sequence, or dictionary. For an [optional](#optional-parameters-in-javascript) parameter, return value, or field, `null` and `undefined` instead leave the value unset.

### Optional Parameters in JavaScript

[Optional parameters](#optional-parameters-and-return-values) use the same mapping as required parameters. The only difference is that `undefined` can be passed as the value of an optional parameter or return value to indicate an "unset" condition. Consider the following operation:

```slice
optional(1) int execute(optional(2) string params, out optional(3) float value);
```

The corresponding proxy method is:

```typescript
execute(
  params?: string | undefined,
  context?: Map<string, string>):
  Ice.AsyncResult<[number | undefined, number | undefined]>;
```

> **Note**
>
> For optional parameters and optional return values, there is not distinction between `null` and `undefined`, both are treated as a not set optional and unmarshall as `undefined`.
