avvio fastify的异步node 应用启动框架

avvio 是fastify 团队开发的一个node 应用异步启动的框架,实现了一些方便的异步处理,同时还可以保证
执行顺序,在实际业务中还是一个比较有用的工具包

参考使用

  • app.js
 
const avvio = require("avvio")()
 
function a (instance, opts, cb) {
  (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) })
  setTimeout(cb, 10)
}
const pointer = a
 
function b (instance, opts, cb) {
  (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) })
  setTimeout(cb, 20)
}
 
function c (instance, opts, cb) {
  (opts.use || []).forEach(_ => { instance.use(_, { use: opts.subUse || [] }) })
  setTimeout(cb, 30)
}
 
avvio
  .use(first, { hello: 'world' })
  .use(duplicate, { count: 0 })
  .use(function a (instance, opts, cb) {
    instance.use(pointer, { use: [b], subUse: [c] })
      .use(b)
    setTimeout(cb, 42)
  })
  .after(function (err, cb) {
    if (err) {
      console.log('something bad happened')
      console.log(err)
    }
    console.log('after first and second')
    cb()
  })
  .use(duplicate, { count: 4 })
  .use(third)
  .ready(function (err) {
    if (err) {
      throw err
    }
    console.log('application booted!')
  })
 
avvio.on('preReady', () => {
  console.log(avvio.prettyPrint())
})
 
function first (instance, opts, cb) {
  console.log('first loaded', opts)
  instance.use(second)
  setTimeout(cb, 42)
}
 
function second (instance, opts, cb) {
  console.log('second loaded')
  process.nextTick(cb)
}
 
function third (instance, opts, cb) {
  console.log('third loaded')
  cb()
}
 
function duplicate (instance, opts, cb) {
  console.log('duplicate loaded', opts.count)
  if (opts.count > 0) {
    instance.use(duplicate, { count: opts.count - 1 })
  }
  setTimeout(cb, 20)
}
  • 运行效果
first loaded { hello: 'world' }
second loaded
duplicate loaded 0
after first and second
duplicate loaded 4
duplicate loaded 3
duplicate loaded 2
duplicate loaded 1
duplicate loaded 0
third loaded
bound root 309 ms
├─┬ first 49 ms
└── second 1 ms
├── duplicate 21 ms
├─┬ a 130 ms
├─┬ a 64 ms
└─┬ b 53 ms
└── c 31 ms
└── b 22 ms
├── bound _after 1 ms
├─┬ duplicate 106 ms
└─┬ duplicate 85 ms
└─┬ duplicate 63 ms
└─┬ duplicate 42 ms
└── duplicate 21 ms
└── third 0 ms
 
application booted!

说明

avvio 在fastify框架中是一个比较重要的,了解一些avvio的机制可以更好的了解fastify的运行机制

参考资料

https://github.com/fastify/avvio
https://github.com/fastify/fastify/blob/main/package.json
https://github.com/fastify/process-warning

posted on 2023-12-05 09:37  荣锋亮  阅读(28)  评论(0编辑  收藏  举报

导航