---
title: Operations and tasks
project: Total.js V4
version: 0.0.99
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/operations-and-tasks/
updated: 2026-11-16T15:41:15.818Z
---

# Operations and tasks

> Reusable business logic with operations, chained operations, tasks with steps, commands, extensions and PROMISIFY().

Operations and tasks are small units of business logic that are not tied to a route. You declare them once and call them from controllers, schemas, schedulers or other operations. An **operation** is one function with a callback. A **task** is a named set of steps that jump from one to another. Both receive a `$` object that carries the value, the errors and, when there is one, the controller of the current request.

## Declare an operation

`NEWOPERATION(name, fn)` registers a function. The function receives `$` and the value. It must finish with `$.callback()`, `$.success()` or `$.invalid()`.

```js
NEWOPERATION('users_count', function($, value) {
	NOSQL('users').count().callback(function(err, count) {
		if (err)
			$.invalid(err);
		else
			$.callback(count);
	});
});
```

Put operations in files in the `/operations/` directory. The framework loads them when the app starts.

## Call an operation

`OPERATION(name, [value], callback, [options], [controller])` runs one operation. The callback receives `err` (an `ErrorBuilder` or `null`), the response and the `options` argument.

```js
OPERATION('users_count', function(err, response) {
	console.log(err, response);
});
```

From a route, pass the controller. Then `$.user`, `$.query`, `$.params`, `$.body` and the other request properties work inside the operation, and the controller callback sends the answer:

```js
exports.install = function() {
	ROUTE('GET /api/users/count/', count);
};

function count() {
	var self = this;
	OPERATION('users_count', self.query, self.callback(), self);
}
```

Without a controller, request properties such as `$.user` or `$.query` are `null`.

### Repeat, stop and bind errors

`NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])` takes extra options:

- `repeat {Number}` runs the operation again when it ends with an error, up to this number of times.
- `stop {Boolean}` (default `true`) stops a `RUN()` chain when this operation fails.
- `binderror {Boolean}` (default `false`) stores the error output as the response of this operation in a `RUN()` chain.
- `filter {String}` is a schema for the query string. `$.filter` then returns the converted query.

```js
NEWOPERATION('newsletter', function($) {
	MAIL($.value.email, 'Newsletter', '=?/mails/newsletter', $.value, $.done());
}, 3);
```

## Chain operations with RUN()

`RUN(names, [value], callback, [options], [controller], [response_name])` runs several operations one after another. `names` is a comma-separated string or an array. All operations share the same `$.value`, so one operation can prepare data for the next.

```js
NEWOPERATION('check', function($) {
	if (!$.value.email) {
		$.invalid('email');
		return;
	}
	$.value.email = $.value.email.toLowerCase();
	$.success();
});

NEWOPERATION('save', function($) {
	NOSQL('contacts').insert($.value).callback($.done());
});

RUN('check, save', { email: 'Peter@Example.com' }, function(err, response) {
	// response.check = { success: true }
	// response.save = { success: true }
	console.log(err, response);
});
```

The response is an object with one key per operation. With `response_name`, the callback receives only the response of that operation:

```js
RUN('check, save', model, function(err, response) {
	// response = { success: true } from "save"
}, 'save');
```

Inside a chain, `$.response` holds the results so far, `$.meta.current` and `$.meta.prev` hold the operation names, and `$.repeated` counts the repeats of the current one. When an operation fails and its `stop` option is `true` (the default), the chain stops and the callback receives the error. An operation name that does not exist is skipped.

## Declare a task

`NEWTASK(name, fn)` declares a set of steps. `fn` receives a `push(step, fn)` function. Each step receives `$` and the value. A step moves on with `$.next(step)` and finishes the task with `$.end()`, `$.success()` or `$.invalid()`.

```js
NEWTASK('order', function(push) {

	push('check', function($, value) {
		if (!value.items || !value.items.length) {
			$.invalid('items');
			return;
		}
		$.next('price');
	});

	push('price', function($, value) {
		value.price = 0;
		for (var item of value.items)
			value.price += item.price * item.count;
		$.next('save');
	});

	push('save', function($, value) {
		NOSQL('orders').insert(value).callback($.done(true));
	});

});
```

Put tasks in files in the `/tasks/` directory.

## Run a task

`TASK(name, step, callback, [options], [value])` creates the task and starts it at `step`. You can also write the name and the step together as `'name/step'`:

```js
TASK('order', 'check', function(err, response) {
	console.log(err, response);
}, { items: [{ price: 10, count: 2 }] });

// The same with "name/step"
TASK('order/check', function(err, response) {
	console.log(err, response);
}, $, $.value);
```

Pass a controller or the `$` of a schema, operation or task as `options` to share its request and its errors. Anything else in `options` is used as the value. `TASK()` returns the task, so you can add steps with `$.push()` before it starts.

`$.next(a, b, ...)` runs the first step that exists, and ends the task when none exists. `$.next2(step)` and `$.done()` return callbacks for asynchronous functions:

```js
push('load', function($, value) {
	NOSQL('orders').one().where('id', value.id).callback($.next2('send'));
});
```

## Commands

Commands are named handlers that any part of the app can trigger. `NEWCOMMAND(name, fn)` adds a handler, and the same name can have several handlers. `CMD(name, [a], [b], [c], [d])` calls all of them.

```js
NEWCOMMAND('clear_prices', function(category) {
	MAIN.prices && delete MAIN.prices[category];
});

CMD('clear_prices', 'books');
```

The framework itself uses commands such as `clear_viewscache`, `clear_smtpcache` and `refresh_tms`.

## Extensions

`NEWEXTENSION(code, [callback], [extend])` installs code at runtime from a string or a URL. The code uses `exports` like a module: `exports.install(next)`, `exports.make()`, `exports.done()` and `exports.uninstall()` are optional. Files in the `/extensions/` directory are installed when the app starts.

## Promises

`PROMISIFY(fn, [a], [b])` wraps a function that ends with a `callback(err, response)` in a `Promise`:

```js
var count = await PROMISIFY(function(callback) {
	NOSQL('users').count().callback(callback);
});
```

The `$` of a schema has a similar `$.promisify()` method; see [Schemas](../../guides/schemas/).
