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

# Operazioni e task

> Funzioni globali e l'oggetto $ di operazioni e task, più comandi, estensioni e PROMISIFY().

Le operazioni (`NEWOPERATION()`, `OPERATION()`, `RUN()`) e i task (`NEWTASK()`, `TASK()`) contengono la logica di business al di fuori delle route. Entrambi ricevono un oggetto `$`; questa pagina elenca le sue proprietà e i suoi metodi, oltre a comandi, estensioni e `PROMISIFY()`. La guida [Operazioni e task](../../guides/operations-and-tasks/) spiega come usarli con esempi; questa pagina è il riferimento esatto.

## API

### NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])

Type: `method`

Registra un'operazione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dell'operazione. |
| `fn` | `Function($, value)` | yes |  | L'operazione. `null` la rimuove. |
| `repeat` | `Number` | no |  | Quante volte eseguire di nuovo l'operazione quando termina con un errore. |
| `stop` | `Boolean` | no | `true` | Ferma una catena `RUN()` quando questa operazione fallisce. |
| `binderror` | `Boolean` | no | `false` | In una catena `RUN()`, memorizza l'output dell'errore come risposta di questa operazione. |
| `filter` | `String` | no |  | Schema per la query string, usato da `$.filter`. |

La funzione riceve `$` e il valore. Deve terminare con `$.callback()`, `$.success()`, `$.invalid()` o un altro metodo che chiama la callback. Un booleano al posto di `repeat` viene letto come `stop`, e una stringa in qualsiasi posizione facoltativa viene letta come `filter`. Chiamare `NEWOPERATION(name, null)` rimuove l'operazione. Metti le operazioni nella directory `/operations/`.

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

Example: Ripetere dopo un errore
```js
NEWOPERATION('ping', function($) {
	RESTBuilder.GET('https://example.com/ping').callback($.done());
}, 3);
```

### OPERATION(name, [value], callback, [options], [controller])

Type: `method`

Esegue una singola operazione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome dell'operazione, oppure URL di un'operazione remota. |
| `value` | `Object` | no | `{}` | Valore per `$.value`. |
| `callback` | `Function(err, response, options)` | yes |  | Chiamata quando l'operazione termina. |
| `options` | `Object` | no |  | Opzioni personalizzate, disponibili come `$.options`. |
| `controller` | `Controller` | no |  | Controller della richiesta corrente, oppure un oggetto `$`. |

La callback riceve `err` (un `ErrorBuilder` o `null`), la risposta e `options`. Quando `value` è una funzione, è la callback e il valore è un oggetto vuoto. Un controller o un oggetto `$` passato come `options` viene usato come controller. Un'operazione mancante termina con l'errore `Operation "name" not found.`

Il nome può anche essere un URL con una scadenza facoltativa, ad esempio `'https://example.com/op.js <5 minutes>'` (sono accettati anche `once` e `asap`). Il file viene scaricato, compilato e messo in cache fino alla scadenza. Può contenere una dichiarazione `NEWOPERATION()` o un modulo con `exports.install`, `exports.make` o `exports.exec`.

Example: Chiamare un'operazione
```js
OPERATION('users_count', function(err, response) {
	console.log(err, response);
});
```

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

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

### RUN(names, [value], callback, [options], [controller], [response_name])

Type: `method`

Esegue più operazioni una dopo l'altra.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `names` | `String|Array` | yes |  | Nomi delle operazioni, separati da virgole. |
| `value` | `Object` | no | `{}` | Valore condiviso per `$.value`. |
| `callback` | `Function(err, response, $)` | yes |  | Chiamata quando la catena termina. |
| `options` | `Object` | no |  | Opzioni personalizzate, disponibili come `$.options`. |
| `controller` | `Controller` | no |  | Controller della richiesta corrente. |
| `response_name` | `String` | no |  | Nome dell'operazione la cui risposta viene restituita da sola. |

`names` è una stringa separata da virgole o un array. Tutte le operazioni condividono un solo `$` e un solo `$.value`. La callback riceve `err`, la risposta e l'oggetto `$`. La risposta ha una chiave per ogni operazione; con `response_name` è solo la risposta di quell'operazione. Quando un'operazione fallisce e la sua opzione `stop` è `true` (il valore predefinito), la catena si ferma. I nomi che non esistono vengono saltati. Una stringa al posto di `options` o `controller` viene letta come `response_name`.

Example: Concatenare due operazioni
```js
RUN('check, save', { email: 'peter@example.com' }, function(err, response) {
	// response.check, response.save
	console.log(err, response);
});
```

Example: Restituire una sola risposta
```js
function create() {
	var self = this;
	RUN('check, save', self.body, self.callback(), null, self, 'save');
}
```

### EACHOPERATION(fn)

Type: `method`

Chiama una funzione per ogni operazione registrata.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function(name)` | yes |  | Chiamata con il nome di ogni operazione. |

La funzione riceve il nome di ogni operazione.

Example: Elencare le operazioni
```js
EACHOPERATION(function(name) {
	console.log(name);
});
```

### $.value

Type: `property`

Il valore passato all'operazione.

Returns: `Object`

`$.model` è lo stesso valore. In una catena `RUN()`, ogni operazione condivide questo oggetto, quindi le modifiche sono visibili alle operazioni successive.

Example: Leggere il valore
```js
NEWOPERATION('greet', function($) {
	$.callback('Hello ' + $.value.name);
});
```

### $.options

Type: `property`

Le opzioni passate a `OPERATION()` o `RUN()`.

Returns: `Object`

Un oggetto vuoto quando non sono state passate opzioni. `OPERATION()` lo ripassa come terzo argomento della callback.

Example: Usare le opzioni
```js
NEWOPERATION('export', function($) {
	$.callback({ format: $.options.format || 'json' });
});

OPERATION('export', {}, console.log, { format: 'csv' });
```

### $.name

Type: `property`

Nome dell'operazione in esecuzione.

Returns: `String`

In una catena `RUN()` cambia con ogni operazione.

Example: Registrare il nome nel log
```js
NEWOPERATION('sync', function($) {
	console.log('Running', $.name);
	$.success();
});
```

### $.error

Type: `property`

L'`ErrorBuilder` dell'operazione.

Returns: `ErrorBuilder`

`$.invalid()` aggiunge qui gli errori. In una catena `RUN()`, ogni operazione riceve un nuovo `ErrorBuilder`.

Example: Aggiungere più errori
```js
NEWOPERATION('validate', function($) {
	!$.value.name && $.error.push('name');
	!$.value.email && $.error.push('email');
	$.callback();
});
```

### $.controller

Type: `property`

Il controller passato all'operazione, oppure `undefined`.

Returns: `Controller`

`$.client` è lo stesso valore. Le proprietà della richiesta di `$` vengono lette da questo controller.

Example: Verificare la presenza di un controller
```js
NEWOPERATION('whoami', function($) {
	if ($.controller)
		$.callback($.user);
	else
		$.invalid('401');
});
```

### $.user

Type: `property`

L'utente della richiesta corrente.

Returns: `Object`

Letto dal controller, oppure `null` senza un controller. Le altre proprietà della richiesta funzionano allo stesso modo: `$.session`, `$.sessionid`, `$.language`, `$.ip`, `$.id`, `$.req`, `$.res`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.ua`, `$.mobile` e `$.test`.

Example: Usare l'utente e la query
```js
NEWOPERATION('my_orders', function($) {
	NOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback);
});
```

### $.filter

Type: `property`

La query string convertita dallo schema `filter` dell'operazione.

Returns: `Object`

Lo schema è l'argomento `filter` di `NEWOPERATION()`, ad esempio `'page:Number,q:String'`. Senza schema restituisce la query grezza. Senza un controller restituisce un oggetto vuoto.

Example: Query tipizzata
```js
NEWOPERATION('products', function($) {
	var filter = $.filter;
	$.callback({ page: filter.page, q: filter.q });
}, 'page:Number,q:String');
```

### $.callback([value])

Type: `method`

Termina l'operazione e restituisce un valore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | no |  | La risposta, oppure un errore. |

Returns: `$`

Un `Error` o un `ErrorBuilder` con errori viene aggiunto a `$.error`. Puoi anche chiamarlo come `$.callback(err, value)`. Quando l'operazione ha errori e restano ripetizioni di `repeat`, viene invece eseguita di nuovo.

Example: Restituire un valore
```js
NEWOPERATION('now', function($) {
	$.callback(NOW);
});
```

Example: Passarlo come callback
```js
NEWOPERATION('users', function($) {
	NOSQL('users').find().callback($.callback);
});
```

### $.success([success], [value])

Type: `method`

Termina l'operazione con un oggetto di successo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `success` | `Boolean` | no | `true` | Il flag di successo. |
| `value` | `Object` | no |  | Un valore aggiunto come `value`. |

Returns: `$`

Restituisce `{ success: true }` alla callback. `$.success(value)` aggiunge `value`. `$.success(false)` imposta `success` a `false`. In una catena `RUN()`, le chiavi vuote vengono omesse.

Example: Restituire il nuovo id
```js
NEWOPERATION('contact_save', function($) {
	var id = UID();
	$.value.id = id;
	NOSQL('contacts').insert($.value).callback(function() {
		$.success(id);
	});
});
```

### $.invalid([name], [error], [path], [index])

Type: `method`

Termina l'operazione con un errore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Error` | no |  | Nome dell'errore, messaggio di errore o `Error`. |
| `error` | `String` | no |  | Messaggio di errore. |
| `path` | `String` | no |  | Percorso del campo. |
| `index` | `Number` | no |  | Indice dell'elemento in un array. |

Returns: `$|Function`

Gli argomenti vanno a `$.error.push()`. Senza argomenti restituisce una funzione `function(err)` che puoi passare come callback.

Example: Restituire un errore
```js
NEWOPERATION('login', function($) {
	if (!$.value.email) {
		$.invalid('email', 'Email is required');
		return;
	}
	$.success();
});
```

### $.done([arg])

Type: `method`

Restituisce una callback che termina l'operazione con un oggetto di successo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `arg` | `Boolean|Object` | no |  | `true` aggiunge la risposta; un altro valore viene aggiunto così com'è. |

Returns: `Function(err, response)`

La funzione restituita `function(err, response)` aggiunge `err` e richiama la callback, oppure la richiama con `{ success: true }`. Con `arg` impostato a `true`, la risposta viene aggiunta come `value`; qualsiasi altro `arg` viene aggiunto al posto della risposta.

Example: Restituire il record inserito
```js
NEWOPERATION('save', function($) {
	NOSQL('contacts').insert($.value).callback($.done(true));
});
```

### $.successful(callback)

Type: `method`

Restituisce una callback che gestisce gli errori per te.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function(a, b, c)` | yes |  | Chiamata quando non c'è alcun errore. |

Returns: `Function(err, a, b, c)`

La funzione restituita `function(err, a, b, c)` chiama `$.invalid(err)` quando c'è un errore, altrimenti chiama `callback(a, b, c)` con `$` come `this`.

Example: Saltare i controlli degli errori
```js
NEWOPERATION('count', function($) {
	NOSQL('users').count().callback($.successful(function(count) {
		$.callback({ count: count });
	}));
});
```

### $.redirect(url)

Type: `method`

Termina l'operazione con un redirect.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | URL di destinazione. |

Returns: `$`

Quando l'operazione è stata chiamata con `controller.callback()`, il controller esegue il redirect a `url`.

Example: Redirect dopo il logout
```js
NEWOPERATION('logout', function($) {
	$.cookie('session', null);
	$.redirect('/');
});
```

### $.noop([nocustomresponse])

Type: `method`

Termina l'operazione senza chiamare la callback.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `nocustomresponse` | `Boolean` | no | `false` | `true` non chiama `controller.custom()`. |

Returns: `$`

Usalo quando l'operazione risponde da sé alla richiesta. Per impostazione predefinita chiama anche `controller.custom()`, così il framework non invia un'altra risposta; `true` salta questa chiamata.

Example: Rispondere da te alla richiesta
```js
NEWOPERATION('ping', function($) {
	$.controller.plain('pong');
	$.noop(true);
});
```

### $.cookie(name, [value], [expire], [options])

Type: `method`

Legge o scrive un cookie della richiesta corrente.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del cookie. |
| `value` | `String` | no |  | Nuovo valore, oppure `null` per rimuoverlo. |
| `expire` | `String|Date` | no |  | Scadenza, ad esempio `'1 day'`. |
| `options` | `Object` | no |  | Opzioni del cookie. |

Returns: `String|$`

Con il solo `name` restituisce il valore del cookie. `null` come `value` rimuove il cookie. Richiede un controller.

Example: Scrivere un cookie
```js
NEWOPERATION('remember', function($) {
	$.cookie('lang', $.value.lang, '1 year');
	$.success();
});
```

### $.variables(str, [data])

Type: `method`

Sostituisce i segnaposto `{key}` in una stringa.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `str` | `String` | yes |  | Testo con segnaposto. |
| `data` | `Object` | no |  | Valori per `{data.key}`. |

Returns: `String`

Le chiavi supportate iniziano con `user.`, `data.`, `model.` o `value.`, `query.` e `params.`. Le chiavi sconosciute vengono mantenute. Funzionano sia le parentesi graffe singole che doppie. Esiste sul `$` di operazioni e task.

Example: Costruire un messaggio
```js
NEWOPERATION('notify', function($) {
	var text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id });
	$.callback(text);
});
```

### $.audit([message], [type])

Type: `method`

Scrive una voce del log di audit per l'operazione.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `message` | `String` | no |  | Messaggio di audit. |
| `type` | `String` | no |  | Tipo della voce. |

Returns: `$`

Chiama `AUDIT($, message, type)` con i dati dell'utente, della richiesta e del valore. Esiste sul `$` di operazioni e task.

Example: Registrare una modifica nell'audit
```js
NEWOPERATION('remove', function($) {
	$.audit('Removed product ' + $.value.id);
	$.success();
});
```

### $.response

Type: `property`

Risultati delle operazioni precedenti in una catena `RUN()`.

Returns: `Object`

Un oggetto con una chiave per ogni operazione già terminata. Impostato solo dentro `RUN()`.

Example: Usare un risultato precedente
```js
NEWOPERATION('invoice', function($) {
	var order = $.response.order;
	$.callback({ total: order.value.price });
});
```

### $.meta

Type: `property`

Informazioni su una catena `RUN()`.

Returns: `Object`

`$.meta.items` è l'elenco dei nomi, `$.meta.current` l'operazione in esecuzione, `$.meta.prev` quella precedente e `$.meta.index` l'indice dell'operazione in esecuzione. Impostato solo dentro `RUN()`.

Example: Controllare l'operazione precedente
```js
NEWOPERATION('save', function($) {
	if ($.meta.prev !== 'check') {
		$.invalid('check');
		return;
	}
	$.success();
});
```

### $.repeated

Type: `property`

Quante volte l'operazione in esecuzione è stata ripetuta in una catena `RUN()`.

Returns: `Number`

Parte da `0` per ogni operazione e cresce ogni volta che l'opzione `repeat` la esegue di nuovo. Impostato solo dentro `RUN()`.

Example: Rinunciare in anticipo
```js
NEWOPERATION('fetch', function($) {
	if ($.repeated > 1)
		console.log('Second retry');
	RESTBuilder.GET('https://example.com/data').callback($.callback);
}, 3);
```

### NEWTASK(name, fn)

Type: `method`

Dichiara un task con step con nome.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del task. |
| `fn` | `Function(push)` | yes |  | Dichiara gli step con `push(step, fn($, value))`. `null` rimuove il task. |

`fn` riceve `push(step, fn)`. Ogni step riceve `$` e il valore, e `this` è `$`. `NEWTASK(name, null)` rimuove il task. Metti i task nella directory `/tasks/`.

Example: Un task con due step
```js
NEWTASK('signup', function(push) {

	push('check', function($, value) {
		if (!value.email) {
			$.invalid('email');
			return;
		}
		$.next('save');
	});

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

});
```

### TASK(name, step, callback, [options], [value])

Type: `method`

Crea un task e lo avvia da uno step.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del task, oppure `'name/step'`. |
| `step` | `String` | yes |  | Il primo step. |
| `callback` | `Function(err, response)` | yes |  | Chiamata quando il task termina. |
| `options` | `Controller|Object` | no |  | Controller o oggetto `$`, oppure il valore. |
| `value` | `Object` | no | `{}` | Valore per `$.value`. |

Returns: `TaskBuilder` Il task, `$`.

`name` e `step` possono essere un'unica stringa `'name/step'`; in tal caso gli argomenti sono `TASK('name/step', callback, [options], [value])`. Un controller o il `$` di uno schema, di un'operazione o di un task come `options` ne condivide la richiesta e gli errori; qualsiasi altro `options` viene usato come valore. Lo step parte al tick successivo, quindi puoi prima aggiungere step con `$.push()`. Senza uno step, avvialo con `$.exec()`.

Il nome può anche essere un URL con una scadenza facoltativa, ad esempio `'https://example.com/task.js <1 hour>'`. Il file viene scaricato e messo in cache fino alla scadenza.

Example: Eseguire un task
```js
TASK('signup', 'check', function(err, response) {
	console.log(err, response);
}, { email: 'peter@example.com' });
```

Example: Da un'azione di uno schema, con "name/step"
```js
TASK('signup/check', $.callback, $, $.model);
```

### $.next(step, [step2], [...])

Type: `method`

Esegue lo step successivo del task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `step` | `String` | yes |  | Nome dello step. Altri nomi vengono provati in ordine. |

Returns: `$`

Esegue il primo step dell'elenco che esiste, prima tra gli step aggiunti con `$.push()` e poi nella dichiarazione del task. Quando non ne esiste nessuno, il task termina. Non fa nulla dopo che il task è terminato.

Example: Passare allo step successivo
```js
push('check', function($, value) {
	$.next(value.paid ? 'ship' : 'pay');
});
```

### $.next2([step])

Type: `method`

Restituisce una callback che passa allo step successivo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `step` | `String` | no |  | Nome dello step successivo. |

Returns: `Function(err)`

La funzione restituita `function(err)` chiama `$.invalid(err)` in caso di errore, altrimenti esegue `step`, oppure termina il task quando `step` è vuoto.

Example: Continuare dopo una scrittura
```js
push('save', function($, value) {
	NOSQL('orders').insert(value).callback($.next2('notify'));
});
```

### $.end([data])

Type: `method`

Termina il task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no | `$.value` | La risposta. |

Returns: `$`

Chiama la callback del task con gli errori (o `null`) e `data`, oppure `$.value` quando `data` è vuoto.

Example: Terminare con il valore
```js
push('price', function($, value) {
	value.total = value.price * value.count;
	$.end();
});
```

### $.end2([send_value])

Type: `method`

Restituisce una callback che termina il task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `send_value` | `Boolean` | no | `false` | `true` restituisce i dati della callback. |

Returns: `Function(err, data)`

La funzione restituita `function(err, data)` chiama `$.invalid(err)` in caso di errore, altrimenti termina il task con `data` quando `send_value` è `true`, oppure con `$.value`.

Example: Terminare con il risultato
```js
push('load', function($, value) {
	NOSQL('orders').one().where('id', value.id).callback($.end2(true));
});
```

### $.success([data])

Type: `method`

Termina il task con un oggetto di successo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `data` | `Object` | no |  | Un valore aggiunto come `value`. |

Returns: `$`

Termina il task con `{ success: true }`, più `value` quando `data` è impostato.

Example: Terminare con successo
```js
push('notify', function($, value) {
	MAIL(value.email, 'Order', '=?/mails/order', value);
	$.success(value.id);
});
```

### $.done([send_value])

Type: `method`

Restituisce una callback che termina il task con un oggetto di successo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `send_value` | `Boolean` | no | `false` | `true` aggiunge i dati della callback come `value`. |

Returns: `Function(err, data)`

La funzione restituita `function(err, data)` chiama `$.invalid(err)` in caso di errore, altrimenti termina il task con `{ success: true }`, più `value: data` quando `send_value` è `true`.

Example: Salvare e terminare
```js
push('save', function($, value) {
	NOSQL('orders').insert(value).callback($.done(true));
});
```

### $.invalid(err, [msg])

Type: `method`

Termina il task con un errore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `err` | `String|Error` | yes |  | Nome dell'errore o `Error`. |
| `msg` | `String` | no |  | Messaggio di errore. |

Returns: `$`

Aggiunge l'errore a `$.error` e termina il task. Non fa nulla dopo che il task è terminato.

Example: Fermare il task
```js
push('check', function($, value) {
	if (!value.items.length)
		$.invalid('items', 'The order is empty');
	else
		$.next('save');
});
```

### $.push(step, fn)

Type: `method`

Aggiunge uno step solo a questo task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `step` | `String` | yes |  | Nome dello step. |
| `fn` | `Function($, value)` | yes |  | Lo step. |

Returns: `$`

Lo step viene usato prima di uno step con lo stesso nome nella dichiarazione del task. Chiamalo sul task restituito da `TASK()`, prima che venga eseguito il primo step.

Example: Sovrascrivere uno step
```js
var task = TASK('signup', 'check', console.log, { email: 'peter@example.com' });
task.push('save', function($, value) {
	$.success();
});
```

### $.exec(step, [callback])

Type: `method`

Avvia il task da uno step.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `step` | `String` | yes |  | Il primo step. |
| `callback` | `Function(err, response)` | no |  | Chiamata quando il task termina. |

Returns: `$`

Imposta la callback se indicata ed esegue `step`. Usalo con un task creato da `TASK(name)` senza uno step.

Example: Avviare più tardi
```js
var task = TASK('signup');
task.value = { email: 'peter@example.com' };
task.exec('check', console.log);
```

### $.callback(fn)

Type: `method`

Imposta la callback del task.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function(err, response)` | yes |  | La callback. |

Returns: `$`

`fn` viene chiamata una volta quando il task termina, con gli errori (o `null`) e la risposta.

Example: Impostare la callback
```js
var task = TASK('signup');
task.callback(function(err, response) {
	console.log(err, response);
});
task.exec('check');
```

### $.value

Type: `property`

Il valore condiviso da tutti gli step del task.

Returns: `Object`

`$.model` è lo stesso valore. Gli step lo ricevono anche come secondo argomento. È un oggetto vuoto quando non è stato passato alcun valore.

Example: Modificare il valore
```js
push('price', function($) {
	$.value.price = 100;
	$.next('save');
});
```

### $.current

Type: `property`

Nome dello step in esecuzione.

Returns: `String`

`$.prev` contiene lo step precedente e `$.name` il nome del task. Le proprietà della richiesta (`$.user`, `$.query`, `$.params`, `$.body` e altre) vengono lette dal controller, come nelle operazioni.

Example: Registrare lo step nel log
```js
push('save', function($) {
	console.log($.name, $.prev, '->', $.current);
	$.success();
});
```

### PROMISIFY(fn, [a], [b])

Type: `method` · Since: `0.0.97`

Avvolge in una Promise una funzione con callback.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | Una funzione il cui ultimo argomento è `callback(err, response)`. |
| `a` | `Object` | no |  | Primo argomento per `fn`. |
| `b` | `Object` | no |  | Secondo argomento per `fn`. |

Returns: `Promise`

Chiama `fn` con gli argomenti dati e una callback `function(err, response)` come ultimo argomento. La promise si risolve con `response` o viene rifiutata con `err`. Gli argomenti vuoti non vengono passati.

Example: Attendere una callback
```js
async function count() {
	var self = this;
	try {
		var response = await PROMISIFY(OPERATION, 'users_count');
		self.json(response);
	} catch (err) {
		self.invalid(err);
	}
}
```

Example: Leggere un file
```js
var body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8');
```

### NEWCOMMAND(name, fn)

Type: `method`

Aggiunge un handler per un comando.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del comando. |
| `fn` | `Function(a, b, c, d)` | yes |  | L'handler. `null` rimuove tutti gli handler. |

Un comando può avere più handler; ogni chiamata ne aggiunge uno. `NEWCOMMAND(name, null)` rimuove tutti gli handler del comando. Eseguilo con `CMD()`.

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

### CMD(name, [a], [b], [c], [d])

Type: `method`

Esegue tutti gli handler di un comando.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del comando. |
| `a` | `Object` | no |  | Primo argomento. |
| `b` | `Object` | no |  | Secondo argomento. |
| `c` | `Object` | no |  | Terzo argomento. |
| `d` | `Object` | no |  | Quarto argomento. |

Passa fino a quattro argomenti a ogni handler. Non fa nulla quando il comando non ha handler. I comandi integrati includono `clear_viewscache`, `clear_smtpcache` e `refresh_tms`.

Example: Eseguire un comando
```js
CMD('clear_prices', 'books');
CMD('clear_viewscache');
```

### CMD2(name, [a], [b], [c], [d])

Type: `method`

Restituisce una funzione che esegue un comando.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Nome del comando. |
| `a` | `Object` | no |  | Primo argomento. |
| `b` | `Object` | no |  | Secondo argomento. |
| `c` | `Object` | no |  | Terzo argomento. |
| `d` | `Object` | no |  | Quarto argomento. |

Returns: `Function`

La funzione restituita esegue tutti gli handler con gli argomenti indicati. Quando il comando non ha handler, restituisce `NOOP`.

Example: Eseguire un comando più tardi
```js
setTimeout(CMD2('clear_viewscache'), 5000);
```

### NEWEXTENSION(code, [callback], [extend])

Type: `method`

Installa un'estensione da codice sorgente o da un URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `String` | yes |  | Codice sorgente, oppure un URL. |
| `callback` | `Function(err, module)` | no |  | Chiamata quando l'estensione è installata. |
| `extend` | `Function(module)` | no |  | Chiamata con il modulo prima che venga installato. |

`code` è JavaScript che imposta `exports`, oppure un URL da cui scaricarlo. Export facoltativi: `id`, `name`, `install(next)`, `make()`, `done()` e `uninstall()`. Senza `id` l'id è un hash di `name` o del codice. Un'estensione con lo stesso id viene prima rimossa. Il codice può anche essere HTML con un blocco `<script total>` e blocchi `<file name="...">`; `exports.files` associa quindi ogni nome di file a un percorso temporaneo. Il metodo aggiunto `remove()` disinstalla l'estensione. I file nella directory `/extensions/` vengono installati all'avvio dell'app.

Example: Installare da una stringa
```js
var code = 'exports.name = \'Hello\';\nexports.make = function() {\n\tROUTE(\'GET /hello/\', function() { this.plain(\'Hello\'); });\n};';

NEWEXTENSION(code, function(err, module) {
	console.log(err, module.id);
});
```

Example: Installare da un URL
```js
NEWEXTENSION('https://example.com/extension.js', function(err, module) {
	err && console.error(err);
});
```

### WORKFLOW(declaration, [tasks])

Type: `method`

Crea una piccola macchina a stati in memoria: step con nome che passano dall'uno all'altro con `$.next()`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `declaration` | `Function` | yes |  | `function($)` che aggiunge gli step. |
| `tasks` | `Object` | no | `{}` | Step come `{ name: function($, value) }`. |

Returns: `Object` Il workflow `$`.

`WORKFLOW()` restituisce un oggetto `$` e lo passa a `declaration($)`, dove aggiungi gli step con `$.push(name, fn)`. Ogni step è `function($, value)`. È un helper locale, non un task registrato: nulla viene memorizzato o nominato a livello globale.

| Membro | Cosa fa |
| --- | --- |
| `$.push(name, fn)` | Aggiunge lo step `fn($, value)` |
| `$.next(name, [value])` | Esegue lo step `name` con `value`; `$.trigger()` è un alias. Un nome sconosciuto distrugge il workflow |
| `$.next2(name)` | Restituisce `function(value)` che esegue `$.next(name, value)`, per le callback |
| `$.invalid(err)` | Chiama `$.error(err, $)` se l'hai impostato, poi distrugge il workflow |
| `$.current`, `$.prev` | Il nome dello step corrente e di quello precedente |
| `$.tasks` | Gli step, come oggetto |
| `$.clone()` | Un nuovo workflow con gli stessi step |
| `$.destroy()` | Lo termina; le chiamate successive di `$.next()` non fanno nulla |

`declaration` può essere `null` quando passi gli step come `tasks`.

Example: Step in ordine
```js
var flow = WORKFLOW(function($) {

	$.error = function(err) {
		console.log('Error:', err);
	};

	$.push('load', function($, id) {
		NOSQL('orders').one().where('id', id).callback(function(err, order) {
			if (order)
				$.next('send', order);
			else
				$.invalid('error-orders-404');
		});
	});

	$.push('send', function($, order) {
		MAIL(order.email, 'Your order', 'mails/order', order);
		$.destroy();
	});

});

flow.next('load', '123');
```
