0

I am trying to use node js promisify to convert the callback to promise inoreder to use await on a async callback function.

I tried different ways to pass the parameter and put loggers

const {promisify} = require('util');
const callbackFn = (firstName, callback) => {
  setTimeout(() => {
    console.log("1");
    if (!firstName)  callback(new Error('no first name passed in!'),null)

    const fullName = `${firstName} IBM`

    callback(null,fullName)
  }, 2000)
}

async function useAwaitEx(){
  try {
    var calbbackfnpromisfied = promisify(callbackFn);
    console.log("3");
    var result = await calbbackfnpromisfied('mayank',  console.log);
    console.log("2");

   console.log("result"+result)
  }catch (error) {
    console.log("error"+error);
  }
}
useAwaitEx();

I am expecting output as 3 1 null 'mayank IBM' 2 null 'mayank IBM'

I am getting output as 3 1 null 'mayank IBM'

Lucifer007
  • 107
  • 1
  • 14

1 Answers1

1

I think a very small change should fix this.

If we want to pass console.log as a parameter we need to declare it separately in the callbackFn function.

The key point here is that we shouldn't pass the last callback to a promisified function when we call it, this will be handled for us.

We won't log exactly what you wish, because result will not be null.

We'll log:

3
1
null 'mayank IBM' 
2
result: mayank IBM

Updated code:

const {promisify} = require('util');
const callbackFn = (firstName, logCallback, callback) => {

setTimeout(() => {
    console.log("1");
    if (!firstName)  callback(new Error('no first name passed in!'),null)

    const fullName = `${firstName} IBM`

    logCallback(null,fullName)
    callback(null,fullName)

}, 2000)
}

async function useAwaitEx(){
try {
    var calbbackfnpromisfied = promisify(callbackFn);
    console.log("3");
    var result = await calbbackfnpromisfied('mayank', console.log);
    console.log("2");
    console.log("result:", result)

// console.log("result"+result)
}catch (error) {
    console.log("error"+error);
}
}
useAwaitEx();
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40