3

目前我已经开始为 Office 2013 开发一些应用程序。为了开发这些应用程序,我使用了 office.js,它旨在与 Excel 工作表一起使用。

大多数 API 类似于:

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
});

我不喜欢这种类型的异步编程。相反,我更喜欢使用Promise并编写如下内容:

document.getSelectedDataAsync(p1, p2)
    .done(function(result)
    {
        // do something with result
    })
    .fail(function(error)
    {
        // show error message 
    })

有没有办法使用上面的承诺来使用 office.js API?

4

2 回答 2

1

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
});
于 2015-04-20T10:13:25.360 回答
0

解决此问题的最简单形式是将回调替换为解决承诺的自定义回调。请注意,以下实现使用了 Chrome 中可用的 ES6 承诺:

        function toPromise () {
            var args = Array.prototype.slice.call(arguments);
            var self = this;
            return new Promise(function (reject, resolve) {
                var callback = function () {
                    if (arguments[0] instanceof Error) {
                        return reject.apply(null, arguments);
                    }

                    resolve.apply(arguments);
                };

                args.push(callback);
                self.apply(self, args);
            });
        }

        Function.prototype.toPromise = toPromise;

        document.getSelectedDataAsync.toPromise(p1, p2).then(function () {
            //success
        }).catch(function () {
            //error
        });
于 2015-04-20T09:56:25.167 回答