koa的洋葱设计模型

async function a(ctx, next) { console.log("invoke a") await next() console.log("exit a") } async function b(ctx, next) { console.log("invoke b") await next() console.log("exit b") } function compose(middleware) { return (ctx, next) => { let index = -1 async function dispatch(i) { if (i <= index) { throw new Error('next() called multiple times') } index = i let fn = middleware[i] if (i === middleware.length) { fn = next } if (!fn) { return } return await fn(ctx, () => { return dispatch(i + 1) }) } return dispatch(0) } } let func = compose([a, b]) func('context', () => { console....

June 5, 2020 · 1 min · Theme PaperMod

NodeJS与ES6的模块化

NodeJS的module 对于 circle.js // 这种导出方式,相当于将变量地址导出,会被外界修改 exports.varA = 'varA' exports.func1 = () => { console.log('func1') } module.exports.varB = 'varB' // 以上写法等价于 module.exports = { varA: 'varA', varB: 'varB', func1 () { console.log('func') } } 在 main.js 中可以这么引入 let math = require('./utils/math') console.log(math.varA) console.log(math.varB) math.func1() math.varA = 'A'; math.varB = 'B'; math.func1 = () => { console.log('another func') } let math2 = require('./utils/math') // varA, varB 和 func1 都发生了改变,证明import进来的模块是单例的 console.log(math2.varA) console.log(math2.varB) math2.func1() ES6的module ES6 模块不是对象,而是通过export命令显式指定输出的代码,再通过import命令输入。...

August 14, 2019 · 1 min · Theme PaperMod

nodejs-异步编程

异步编程 callback瀑布级回调 Promise Generator Async 和 Await 在函数体前通过关键字async可以将函数变为async函数 在async函数中对需要异步执行的函数前需加await关键字 await后的函数必须使用Promise对象封装 async函数执行后返回的是一个Promise对象 NodeJs单线程是怎么保证效率的

October 6, 2018 · 1 min · Theme PaperMod