Home > Enterprise >  Promisify a curried (higher order function) callback
Promisify a curried (higher order function) callback

Time:12-08

I am trying to promisify (or leverage async await feature) the callback in the function getId, using new Promise(resolve => ..., but because of the usage of the higher order function getAddresses, I am a bit stumped. I am not great at functional programming. Any suggestions on how do I promisify this one?

const {queryRecord, getData} = require(“@xyzLib”);

const getId = (callback) => {
    getData(“attr1”,”attr2”,getAddresses(callback));
}

const getAddresses = (callback) => (result) => {
    if (!result.success) {
      callback(new Error(‘Exception details’))
    } else {
      queryRecord(objectName, (result) => {
        callback(null, result.name);
    });
   }
}
// invoking call

getId(async (error, zip, state) => {
if (error) {
    console.log(error.message)
} else {
 await fetch(encodeURI(settingsUrl), {
    method: 'GET',
});
....

CodePudding user response:

Since getId() accepts a callback as the last argument and that callback uses the nodejs calling convention, you can just directly use util.promisify() on getId like this:

const { promisify } = require('util');

const getIdPromise = promisify(getId);

getIdPromise().then(result => {
    console.log(result);
    let fetchResult = await fetch(...);
    ...
}).catch(err => {
    console.log(err);
});

Or, if you're already inside an async function body:

try {
    const result = await getIdPromise();
    console.log(result);
    const fetchResult = await fetch(...);
    ...
} catch (err) {
    console.log(err);
}

CodePudding user response:

You should promisify on the lowest level available, i.e. the imported functions from the library. Then you don't even need that currying. With

const { promisify } = require('util');
const xyz = require(“@xyzLib”);
const queryRecord = promisify(xyz.queryRecord);
const getData = promisify(xyz.getData);

you can write simply

async function getId() {
    return getAddresses(await getData("attr1", "attr2"));
}

async function getAddresses(data) {
  if (!data.success) throw new Error("Exception details");
  const result = await queryRecord(objectName);
  return result.name;
}

// invoking call
try {
  const zip = getId();
  await fetch(encodeURI(settingsUrl), {
    method: 'GET',
  });
} catch(error) {
  console.log(error.message);
}
  • Related