(* I modified my initial question... *)
I have an asynchronous function calculate
which re-calculates a Excel workbook and prints how long it takes.
Then, I want to make the function to return the calculation time, so that I could record it. It regards making an asynchronous function return a value. I read several threads, and write the following 2 ways, which work:
function calculate1 (mode, fn) {
return Excel.run(function (ctx) {
ctx.workbook.application.calculate(mode);
var before = performance.now();
return ctx.sync().then(function() {
var after = performance.now();
var t = after - before;
document.getElementById("b").value += 'inside: ' + t + '\n';
fn(t);
})
})
}
function calculate2 (mode) {
return new Promise(function (resolve, reject) {
return Excel.run(function (ctx) {
ctx.workbook.application.calculate(mode);
var before = performance.now();
return ctx.sync().then(function() {
var after = performance.now();
var t = after - before;
document.getElementById("b").value += 'inside: ' + t + '\n';
resolve(t); })
})
})
}
Here is the test:
function test () {
var a = [];
var pm = new OfficeExtension.Promise(function(resolve, reject) { resolve (null); });
pm
.then(function() { return calculate1('FullRebuild', function (t) {
a.push(t); }); })
.then(function() { return calculate1('FullRebuild', function (t) {
a.push(t); }); })
.then(function() { return calculate2('FullRebuild').then(function (result) {
a.push(result); }); })
.then(function() { return calculate2('FullRebuild').then(function (result) {
a.push(result); }); })
.then(function() {
document.getElementById("b").value += a.toString() + '\n'; });
}
I guess calculate1
uses callback
, while calculate2
uses promise
. Could anyone tell me which way is better?
Additionally, is fn(t)
(resp., resolve(t)
) in the right place, or should I wrap it in another then
?
PS: Excel.run
and ctx.sync()
are functions of JavaScript API for Office; they both return a promise.