How do I convert an existing callback API to promises?

General Tech Bugs & Fixes 2 months ago

1 15 3 0 1 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 27 Aug 2024, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (15)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer 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:

window.onload; // set to callback
...
window.onload = function() {

};

2. Plain callback:

function request(onChangeHandler) {
    ...
}
request(function() {
    // change happened
    ...
});

3. Node style callback ("nodeback"):

function getStuff(dat, callback) {
    ...
}
getStuff("dataParam", function(err, data) {
    ...
})

4. A whole library with node style callbacks:

API;
API.one(function(err, data) {
    API.two(function(err, data2) {
        API.three(function(err, data3) {
            ...
        });
    });
});

How do I work with the API in promises, how do I "promisify" it?

profilepic.png
manpreet 2 years ago

You can do something like this

// @flow

const toPromise = (f: (any) => void) => {
  return new Promise<any>((resolve, reject) => {
    try {
      f((result) => {
        resolve(result)
      })
    } catch (e) {
      reject(e)
    }
  })
}

export default toPromise

Then use it

async loadData() {
  const friends = await toPromise(FriendsManager.loadFriends)

  console.log(friends)
}

 

1 views   1 shares

profilepic.png
manpreet 2 years ago

es6-promisify converts callback-based functions to Promise-based functions.

const promisify = require('es6-promisify');

const promisedFn = promisify(callbackedFn, args);

Ref: https://www.npmjs.com/package/es6-promisify

 

1 views   1 shares

profilepic.png
manpreet 2 years ago

My promisify version of a callback function is the P function:

 

var P = function() {
  var self = this;
  var method = arguments[0];
  var params = Array.prototype.slice.call(arguments, 1);
  return new Promise((resolve, reject) => {
    if (method && typeof(method) == 'function') {
      params.push(function(err, state) {
        if (!err) return resolve(state)
        else return reject(err);
      });
      method.apply(self, params);
    } else return reject(new Error('not a function'));
  });
}
var callback = function(par, callback) {
  var rnd = Math.floor(Math.random() * 2) + 1;
  return rnd > 1 ? callback(null, par) : callback(new Error("trap"));
}

callback("callback", (err, state) => err ? console.error(err) : console.log(state))
callback("callback", (err, state) => err ? console.error(err) : console.log(state))
callback("callback", (err, state) => err ? console.error(err) : console.log(state))
callback("callback"
                                                    
                                                    
1 views   1 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.