nodejs 几个不错的callback 以及promise 转换处理工具
nodejs 的一步调用经历了,callback -> promise -> async await(语法糖) 模式的转变
以下是几个整理
nodejs 自带的callback -> promise 处理
util 工具包
- 参考使用
const util = require("util") function login({name,age},cb) { cb(null,{name,age}); } const fn = util.promisify(login); (async () => { let result = await fn({ name:"dalong", age:333 }) console.log(result) })()
pify
一个很不错的callback -> promise 转换处理
- 参考使用
const pify = require("pify") function login({name,age},cb) { cb(null,{name,age}); } const fn = pify(login); (async () => { let result = await fn({ name:"dalong", age:333 }) console.log(result) })()
universalify
这个工具就更方便了可以,callback -> promise-> 也可以promise-> promise
- 参考使用
callback->prormise
const universalify = require("universalify"); function login({name,age},cb) { cb(null,{name,age}); } const fn = universalify.fromCallback(login); (async()=>{ const result = await fn({ name:"dalong", age:333 }) console.log(result) })()
promise -> promise
const universalify = require("universalify"); async function promiseFn({name,age}){ return { name, age, version:"v2" } }; const fn = universalify.fromPromise(promiseFn); ? (async()=>{ const result = await fn({ name:"dalong", age:333 }) console.log(result) })()
## 说明
以上是几个整理,实际上类似的npm 包还是很多的,可以通过npm官方仓库查找相关的
参考资料
https://www.npmjs.com/package/universalify
https://www.npmjs.com/package/pify
相关推荐
前端开发Kingcean 2020-05-29
89500297 2020-04-29
nmgxzm00 2020-11-10
xixixi 2020-11-11
88254251 2020-11-01
MarukoMa 2020-09-02
88234852 2020-09-15
陈旭阳 2020-08-31
whynotgonow 2020-08-19
前端开发Kingcean 2020-07-30
whynotgonow 2020-07-29
bowean 2020-07-08
前端开发Kingcean 2020-07-08
88520191 2020-07-05
前端开发Kingcean 2020-06-27
88481456 2020-06-18
whynotgonow 2020-06-16
88520191 2020-06-13