1

I would like to create a promisify wrapper method, where the callback is customisable method and user can provide, I will send this method as a parameter to the promisify method, it should return me a promise with resolve and reject callbacks.

Here is my sample for creating a wrapper for promisify:

function promisify(callback) {
  var promise1= new Promise(function(resolve,reject){
    callback(resolve);
   // resolve();
  })

  return promise1;
}

function myTimer(resolve) {
  setTimeout(function(){
    console.log('hello');
    resolve();
  },2000);
}

promisify(myTimer).then(function(){
  alert("jello");
})

Is this the right approach to call the resolve in the promisify, and how can I catch the error?

halfer
  • 19,824
  • 17
  • 99
  • 186
Geeky
  • 7,420
  • 2
  • 24
  • 50
  • 2
    *"where the callback is customisable method and user can provide"* Why not have the user return a promise from their function? No need to promisify anything. Promisifying is really a stop-gap solution for old APIs. – Felix Kling Dec 17 '18 at 21:24
  • so you mean, user method returns a promise on its own. I am trying to achieve nodejs promisify, which i think is on the similar lines as above – Geeky Dec 17 '18 at 21:26
  • This is more a question for [CodeReview](https://codereview.stackexchange.com/), unless you have a problem with the code? – trincot Dec 17 '18 at 21:32
  • No ,i want to know how can i achieve promisify ,just added the code to show what i have tried – Geeky Dec 17 '18 at 21:33
  • It's unclear what you mean by "*it should return me a promise with resolve and reject callbacks.*" As it stands, the code you posted works as expected, what else are you looking for? – Bergi Dec 17 '18 at 21:34
  • 3
    You can just look at the source if you're trying to mirror the function: https://github.com/nodejs/node/blob/master/lib/internal/util.js#L261-L296 – zero298 Dec 17 '18 at 21:36
  • @Bergi i am trying to achieve promisify, but in my code every custom callback method has to call the resolve method, the customcallback should not be changed that is what i am trying to achieve – Geeky Dec 17 '18 at 21:37
  • @Geeky What else would your "custom callback" call? It *has* to call something - just like `setTimeout` calls its callback. – Bergi Dec 17 '18 at 21:38
  • 1
    You'll want to take a look at [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/1048572) – Bergi Dec 17 '18 at 21:39
  • Ok thanks for the response – Geeky Dec 17 '18 at 21:41
  • you might want to check how libs like bluebird implements promisify if used in production(DRY) https://github.com/petkaantonov/bluebird/blob/master/src/promisify.js – ABOS Dec 17 '18 at 21:54

0 Answers0