Skip to content
当前有符合你浏览器所设置语言的版本,是否前往zh-CN版本的网站?
There is a version suitable for your browser's language settings. Would you like to go to the zh-CN language of the site?
HomeDocument

Use

H1

You might want to separate certain pieces of code that can be used by different APIs, such as sending emails or connecting to a database. In Milkio, the best way to achieve this is by writing them as “uses”. Typically, we place these “uses” under the /src/uses directory, but you can actually place them anywhere, including within the /src/apps directory.

Lifecycle

Each “use” is a singleton and lazily loaded. It is only executed the first time it is used and only executed once. Subsequent calls will return the same content as the initial call.

Writing

As a convention, we prefix the variable names exported by each feature with “use”. Let’s take an addition and subtraction calculator as an example:

import { defineUse } from "milkio";
export const useCalculator = defineUse(async () => {
return {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
// ...
};
});

You can call it from anywhere in your code:

const calculator = await useCalculator();
calculator.add(1, 3); // Output: 4
calculator.subtract(1, 3); // Output: -2