function generate(count) {
var founded = false,
_sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
str = '';
while(!founded) {
for(var i = 0; i < count; i++) {
str += _sym[parseInt(Math.random() * (_sym.length))];
}
base.getID(string, function(err, res) {
if(!res.length) {
founded = true; // How to do it?
}
});
}
return str;
}
如何设置一个变量值与数据库查询回调?我该怎么做呢?
这里是目前解决方案的一个基准,参考纳米基准
import { v4 as uuid4 } from 'uuid'
import benchmark from 'benchmark'
import shortid from 'shortid'
let suite = new benchmark.Suite()
suite
.add('crypto.randomUUID', () => {
crypto.randomUUID()
})
.add('nanoid', () => {
nanoid()
})
.add('uuid v4', () => {
uuid4()
})
.add("math.random", () => {
(new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)
})
.add('crypto.randomBytes', () => {
crypto.randomBytes(32).toString('hex')
})
.add('shortid', () => {
shortid()
})
.on('cycle', event => {
let name = event.target.name
let hz = formatNumber(event.target.hz.toFixed(0)).padStart(10)
process.stdout.write(`${name}${pico.bold(hz)}${pico.dim(' ops/sec')}\n`)
})
.run()
结果是
node ./test/benchmark.js
crypto.randomUUID 13,281,440 ops/sec
nanoid 3,278,757 ops/sec
uuid v4 1,117,140 ops/sec
math.random 1,206,105 ops/sec
crypto.randomBytes 280,199 ops/sec
shortid 30,728 ops/sec
测试env:
2.6 GHz 6Cores Intel酷睿i7 MacOS
节点v16.17.0