I'm writting some library that will provide asynchronous methods, I want the user to be able to use classic callbacks or modern promises depending on its own preference.
I was coding two versions of each methods by naming them 'myMethod' and 'myMethodPromise', then a thought came accross my mind :
Why not coding a method that combines the two patterns?
One single method with an optional callback argument, if not provided then the method returns a promise instead of calling the callback.
Would it be a good practice?
// Promise-callback combined pattern method
function myAsyncMethod ( callback = null ) {
if(callback) {
var result = "xxx";
// Do something...
callback(result);
} else {
return(new Promise((res, rej) => {
var result = "xxx";
// Do something...
res(result);
}))
}
}
// Usage with callback
myAsyncMethod((result)=>document.getElementById('callbackSpan').innerHTML = result);
// or with promise
myAsyncMethod().then((result) => document.getElementById('promiseSpan').innerHTML = result);
<p>
Result with callback : <span id="callbackSpan"></span>
</p>
<p>
Result with promise : <span id="promiseSpan"></span>
</p>
**
Aucun commentaire:
Enregistrer un commentaire