# Chiamare un'azione dal tuo codice

> Usa ACTION() per eseguire un'azione da un timer, un job o un'altra azione, con payload, query e utente propri.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: it
Content-SHA256: 983bdfe8f391e1badd1d7e7ab9c546d2239d557411249455ec9e6d6f6bcfded2
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`ACTION(name, payload)` restituisce un chiamante che esegue l'azione con tutta la sua validazione, esattamente come se arrivasse da una route. Il secondo argomento è il payload (l'input). Concatena `.query()` e `.user()` per darle più dati e termina con `.callback(function(err, response) {})` oppure `.promise()` (da usare con `await`). Quando i dati non sono validi, `err` è un error builder invece di un'eccezione.

```js definitions/math.js
NEWACTION('Math/add', {
	name: 'Add two numbers',
	input: '*a:Number, *b:Number',
	action: function($, model) {
		$.callback({ sum: model.a + model.b });
	}
});
```

```js controllers/math.js
exports.install = function() {
	ROUTE('GET /sum/', sum);
	ROUTE('GET /sum-promise/', sum_promise);
};

function sum($) {
	ACTION('Math/add', { a: '2', b: '3' }).callback(function(err, response) {
		if (err)
			$.invalid(err);
		else
			$.json(response);
	});
}

async function sum_promise($) {
	try {
		var response = await ACTION('Math/add', { a: 10, b: 5 }).promise();
		$.json(response);
	} catch (err) {
		$.invalid(400);
	}
}
```
