Speak now
Please Wait Image Converting Into Text...
Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Challenge yourself and boost your learning! Start the quiz now to earn credits.
Unlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
General Tech Bugs & Fixes 2 months ago
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.
Turn Your Knowledge into Earnings.
I want to work with promises but I have a callback API in a format like:
window.onload; // set to callback ... window.onload = function() { };
function request(onChangeHandler) { ... } request(function() { // change happened ... });
function getStuff(dat, callback) { ... } getStuff("dataParam", function(err, data) { ... })
API; API.one(function(err, data) { API.two(function(err, data2) { API.three(function(err, data3) { ... }); }); });
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:
function.prototype.apply
function.prototype.push
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.
With plain old vanilla javaScript, here's a solution to promisify an api callback.
function get(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('get', url); xhr.addEventListener('readystatechange', function () { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log('successful ... should call callback ... '); callback(null, JSON.parse(xhr.responseText)); } else { console.log('error ... callback with error data ... '); callback(xhr, null); } } }); xhr.send(); } /** * @function promisify: convert api based callbacks to promises * @description takes in a factory function and promisifies it * @params {function} input function to promisify * @params {array} an array of inputs to the function to be promisified * @return {function} promisified function * */ function promisify(fn) { return function () { var args = Array.prototype.slice.call(arguments); return new Promise(function(resolve, reject) { fn.apply(null, args.concat(function (err, result) { if (err) reject(err); else resolve(result); })); }); } } var get_promisified = promisify(get); var promise = get_promisified('some_url'); promise.then(function (data) { // corresponds to the resolve function console.log('successful operation: ', data); }, function (error) { console.log(error); });
In Node.js 8 you can promisify object methods on the fly using this npm module:
https://www.npmjs.com/package/doasync
It uses util.promisify and Proxies so that your objects stay unchanged. Memoization is also done with the use of WeakMaps). Here are some examples:
With objects:
const fs = require('fs'); const doAsync = require('doasync'); doAsync(fs).readFile('package.json', 'utf8') .then(result => { console.dir(JSON.parse(result), {colors: true}); });
With functions:
doAsync(request)('http://www.google.com') .then(({body}) => { console.log(body); // ... });
You can even use native call and apply to bind some context:
call
apply
doAsync(myFunc).apply(context, params) .then(result => { /*...*/ });
You can use native Promise in ES6, for exemple dealing with setTimeout:
enqueue(data) { const queue = this; // returns the Promise return new Promise(function (resolve, reject) { setTimeout(()=> { queue.source.push(data); resolve(queue); //call native resolve when finish } , 10); // resolve() will be called in 10 ms }); }
In this exemple, the Promise has no reason to fail, so reject() is never called.
reject()
es6-promisify converts callback-based functions to Promise-based functions.
es6-promisify
const promisify = require('es6-promisify'); const promisedFn = promisify(callbackedFn, args);
Ref: https://www.npmjs.com/package/es6-promisify
My promisify version of a callback function is the P function:
callback
P
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" REPLY 1 views 0 likes 1 shares Facebook Twitter Linked In WhatsApp
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.
General Tech 9 Answers
General Tech 7 Answers
General Tech 3 Answers
General Tech 2 Answers
Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.