commandBus.executeSync¶
The executeSync
method allows to execute a command synchronously.
Input parameters¶
command¶
command
is a mandatory parameter of the BaseMessage type which represents the command to be executed.
type
of the Command Bus messages should always be command
options (optional)¶
options
is a mandatory parameter of the TMessageExecutionOptions type which represents the additional options of a command.
Returned value¶
A returned value has a type of any
which is a command handler return type if such handler exists. This will be shown in the examples below.
Example¶
To executeSync a command of the Command Bus you can use the executeSync
method:
useStorefront(async (storefront) => {
storefront.commandBus.executeSync({
name: 'my-command',
type: 'command',
body: 'command body'
});
});
Your body can contain any data type you need:
useStorefront(async (storefront) => {
storefront.commandBus.executeSync({
name: 'my-command',
type: 'command',
body: [
{
name: 'example1',
values: [1, 2, 3]
},
{
name: 'example2',
values: [10, 20, 30]
}
]
});
});
Example¶
In this example we execute a command of the Command Bus synchronously and listen to it:
useStorefront(async (storefront) => {
storefront.commandBus.on('get-body-length', function ({ body }) {
const bodyLength = typeof body === 'string' ? body.length : 0;
return bodyLength;
});
const bodyLength = storefront.commandBus.executeSync({
name: 'get-body-length',
type: 'command',
body: 'command body'
});
console.log('body length:', bodyLength);
});