-
Notifications
You must be signed in to change notification settings - Fork 0
08 Return values
In this chapter you'll learn how to use the values returned by methods.
Your methods don't have to return anything. They will still be chaineable, because the context (what's accesses as, testCtx[0]
, testCtx[1]
, etc.) takes care of it.
The same holds true for async functions returning promises that resolve to undefined.
If you return an array, you'll be able to access its elements in two different ways.
The most straightforward way to access the returned items is to use await
.
Given this is your method:
{
name: 'testmodule',
methods: {
testMethod: function () {
return [42, 1337];
}
}
}
Then this is a straightforward way to access the results:
const [a, b] = await testCtx[0].testmoduleTestMethod();
Please note the methods are always asynchronous when used through the context, even if the method you registered is synchronous.
However, there's a far more interesting way to use the returned values and it's chaining.
If testMethod
returns [42, 1337]
, that is an array, then the items of this array will become the arguments passed to the next method call.
Let's say we have a testConsume
method like this:
{
// ...
methods: {
// ...
testConsume: function (a, b) {
console.log(a, b);
//...
Then the code below will console.log 42, 1337
:
testCtx[0]
.testmoduleTestMethod()
.testmoduleTestConsume()
It's recommended you return arrays, so that the return values can be consumed by other modules without the need of breaking that neat chain of methods.
Even if you need to return just one item and you don't see a reason why would somebody want to use it in their module, you can still return a one-element array. That way if somebody eventually wants to chain it, they'll be able to do it.
Nevertheless, if you want to return a single value, you can do it:
{
// ...
methods: {
// ...
singleValue: function () {
return 42;
//...
If you don't return an array, then this is the only way how you can use the results:
const fortyTwo = await testCtx[0].testmoduleSingleValue();