Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with office.js using promise pattern

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?

like image 288
mehrandvd Avatar asked Jan 22 '26 07:01

mehrandvd


1 Answers

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
});
like image 127
Benjamin Gruenbaum Avatar answered Jan 23 '26 19:01

Benjamin Gruenbaum