Edit Page

.initialize

The initialize feature allows a hook to perform startup tasks that may be asynchronous or rely on other hooks. All Sails configuration is guaranteed to be completed before a hook’s initialize function runs. Examples of tasks that you may want to put in initialize include:

  • logging in to a remote API
  • reading from a database that will be used by hook methods
  • loading support files from a user-configured directory
  • waiting for another hook to load first

Like all hook features, initialize is optional and can be left out of your hook definition. If implemented, initialize should be an async function which must be resolved (i.e. not throw or hang forever) in order for Sails to finish loading:

initialize: async function() {

   // Do some stuff here to initialize hook

}
Hook timeout settings

By default, hooks have ten seconds to complete their initialize function and resolve before Sails throws an error. That timeout can be configured by setting the _hookTimeout key to the number of milliseconds that Sails should wait. This can be done in the hook’s defaults:

defaults: {
   __configKey__: {
      _hookTimeout: 20000 // wait 20 seconds before timing out
   }
}
Hook events and dependencies

When a hook successfully initializes, it emits an event with the following name:

hook:<hook name>:loaded

For example:

  • the core orm hook emits hook:orm:loaded after its initialization is complete
  • a hook installed into node_modules/sails-hook-foo emits hook:foo:loaded by default
  • the same sails-hook-foo hook, with sails.config.installedHooks['sails-hook-foo'].name set to bar would emit hook:bar:loaded
  • a hook installed into node_modules/mygreathook would emit hook:mygreathook:loaded
  • a hook installed into api/hooks/mygreathook would also emit hook:mygreathook:loaded

You can use the "hook loaded" events to make one hook dependent on another. To do so, simply wrap your hook’s initialize logic in a call to sails.on(). For example, to make your hook wait for the orm hook to load, you could make your initialize similar to the following:

initialize: async function() {
  return new Promise((resolve)=>{
    sails.on('hook:orm:loaded', ()=>{
      // Finish initializing custom hook
      // Then resolve.
      resolve();
    });
  });
}

To make a hook dependent on several others, gather the event names to wait for into an array and call sails.after:

initialize: async function() {
  return new Promise((resolve)=>{
    var eventsToWaitFor = ['hook:orm:loaded', 'hook:mygreathook:loaded'];
    sails.after(eventsToWaitFor, ()=>{
      resolve();
    });
  });
}

Is something missing?

If you notice something we've missed or could be improved on, please follow this link and submit a pull request to the sails repo. Once we merge it, the changes will be reflected on the website the next time it is deployed.

Sails logo
  • Home
  • Get started
  • Support
  • Documentation
  • Documentation

For a better experience on sailsjs.com, update your browser.

Check out the full Sailsconf 2022 playlist on Youtube

Tweet Follow @sailsjs

Documentation

Reference Concepts App structure | Upgrading Contribution guide | Tutorials More

Concepts

  • Actions and controllers
    • Generating actions and controllers
    • Routing to actions
  • Assets
    • Default tasks
    • Disabling Grunt
    • Task automation
  • Blueprints
    • Blueprint actions
    • Blueprint routes
  • Configuration
    • The local.js file
    • Using `.sailsrc` files
  • Deployment
    • FAQ
    • Hosting
    • Scaling
  • E-commerce
  • Extending Sails
    • Adapters
      • Available adapters
      • Custom adapters
    • Custom responses
      • Adding a custom response
    • Generators
      • Available generators
      • Custom generators
    • Hooks
      • Available hooks
      • Events
      • Hook specification
        • .configure
        • .defaults
        • .initialize()
        • .registerActions()
        • .routes
      • Installable hooks
      • Project hooks
      • Using hooks
  • File uploads
    • Uploading to GridFS
    • Uploading to S3
  • Globals
    • Disabling globals
  • Helpers
    • Example helper
  • Internationalization
    • Locales
    • Translating dynamic content
  • Logging
    • Custom log messages
  • Middleware
    • Conventional defaults
  • Models and ORM
    • Associations
      • Many-to-many
      • One way association
      • One-to-many
      • One-to-one
      • Reflexive associations
      • Through associations
    • Attributes
    • Errors
    • Lifecycle callbacks
    • Model settings
    • Models
    • Query language
    • Records
    • Standalone Waterline usage
    • Validations
  • Policies
    • Access Control and Permissions
  • Programmatic usage
    • Tips and tricks
  • Realtime
    • Multi-server environments
    • On the client
    • On the server
  • Routes
    • Custom routes
    • URL slugs
  • Security
    • Clickjacking
    • Content security policy
    • CORS
    • CSRF
    • DDOS
    • P3P
    • Socket hijacking
    • Strict Transport Security
    • XSS
  • Services
  • Sessions
  • Shell scripts
  • Testing
  • Views
    • Layouts
    • Locals
    • Partials
    • View engines

Built with Love

The Sails framework is built by a web & mobile shop in Austin, TX, with the help of our contributors. We created Sails in 2012 to assist us on Node.js projects. Naturally we open-sourced it. We hope it makes your life a little bit easier!

Sails:
  • What is Sails?
  • Community
  • News
  • For business
About:
  • Our company
  • Security
  • Legal
  • Logos/artwork
Help:
  • Get started
  • Documentation
  • Docs
  • Contribute
  • Take a class

© 2012-2022 The Sails Company. 
The Sails framework is free and open-source under the MIT License. 
Illustrations by Edamame.