Currently I've started developing some Apps for Office 2013. To develop these apps I'm using office.js which is designed to work with Excel worksheets for example.
Most of the APIs are like:
document.getSelectedDataAsync(p1, p2, function(asyncResult)
{
if (asyncResult.status == 'success')
// do something with asyncResult.value
else if (asyncResult.status == 'fail')
// show asyncResult.error as Error
});
I don't like this type of asynchronous programming. Rather I prefer to use promises and write something like:
document.getSelectedDataAsync(p1, p2)
.done(function(result)
{
// do something with result
})
.fail(function(error)
{
// show error message
})
Is there any way to use office.js API using promises like above?
Sure thing - this example is using the bluebird promise library. Basically, we're converting a callback API to promises:
function promisify(fn){ // take a function and return a promise version
return function(){
var args = [].slice.call(arguments);
return new Promise(function(resolve, reject){
args.push(function(asyncResult){
if(asyncResult.status === 'success') resolve(asyncResult.value);
else reject(asyncResult.error);
});
fn.apply(this, args); // call function
}.bind(this)); // fixate `this`
};
}
This would let you do something like:
document.getSelectedDataPromise = promisify(document.getSelectedDataAsync);
document.getSelectedDataPromise(p1, p2).then(function(result){
// do something with result
}).catch(function(err){
// handle error
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With