前端开发Kingcean 2020-06-11
nodejs 的一步调用经历了,callback -> promise -> async await(语法糖) 模式的转变
以下是几个整理
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) })()
一个很不错的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) })()
这个工具就更方便了可以,callback -> promise-> 也可以promise-> promise
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