The callback style function always like this(almost all function in node.js is this style):
//fs.readdir(path[, options], callback)
fs.readdir('mypath',(err,files)=>console.log(files))
This style has same feature:
-
the callback function is passed by last argument.
-
the callback function always accept the error object as it's first argument.
So, you could write a function for convert a function with this style like this:
const R =require('ramda')
/**
* A convenient function for handle error in callback function.
* Accept two function res(resolve) and rej(reject) ,
* return a wrap function that accept a list arguments,
* the first argument as error, if error is null,
* the res function will call,else the rej function.
* @param {function} res the function which will call when no error throw
* @param {function} rej the function which will call when error occur
* @return {function} return a function that accept a list arguments,
* the first argument as error, if error is null, the res function
* will call,else the rej function
**/
const checkErr = (res, rej) => (err, ...data) => R.ifElse(
R.propEq('err', null),
R.compose(
res,
R.prop('data')
),
R.compose(
rej,
R.prop('err')
)
)({err, data})
/**
* wrap the callback style function to Promise style function,
* the callback style function must restrict by convention:
* 1. the function must put the callback function where the last of arguments,
* such as (arg1,arg2,arg3,arg...,callback)
* 2. the callback function must call as callback(err,arg1,arg2,arg...)
* @param {function} fun the callback style function to transform
* @return {function} return the new function that will return a Promise,
* while the origin function throw a error, the Promise will be Promise.reject(error),
* while the origin function work fine, the Promise will be Promise.resolve(args: array),
* the args is which callback function accept
* */
const toPromise = (fun) => (...args) => new Promise(
(res, rej) => R.apply(
fun,
R.append(
checkErr(res, rej),
args
)
)
)
For more concise, above example used ramda.js. Ramda.js is a excellent library for functional programming. In above code, we used it's apply(like javascript function.prototype.apply
) and append(like javascript function.prototype.push
). So, we could convert the a callback style function to promise style function now:
const {readdir} = require('fs')
const readdirP = toPromise(readdir)
readdir(Path)
.then(
(files) => console.log(files),
(err) => console.log(err)
)
toPromise and checkErr function is own by berserk library, it's a functional programming library fork by ramda.js(create by me).
Hope this answer is useful for you.
manpreet
Best Answer
2 years ago
I want to work with promises but I have a callback API in a format like:
1. DOM load or other one time event:
2. Plain callback:
3. Node style callback ("nodeback"):
4. A whole library with node style callbacks:
How do I work with the API in promises, how do I "promisify" it?