context.sync - chaining
If you do not want to nest the 'context.sync' you can use chaining instead.
There are two different ways you can layout your code when you use chaining.
The first syntax we are calling Invoke Chaining and the other syntax we are calling Reference Chaining.
Invoke Chaining Syntax
This first chaining layout requires you to return 'context.sync()' multiple times.
The body of each '.then' must either be fully synchronous or return a promise.
return context.sync()
.then(function () {
return context.sync();
})
.then(function () {
return context.sync();
Example - Invoke Chaining Syntax
This writes data to cell "A1", writes data to cell "B1", retrieves the value from cell "A1" and writes data to cell "C1".
Excel.run(function (context) {
let _workbook = context.workbook;
let _sheet = _workbook.worksheets.add();
let _range1 = _sheet.getRange('A1');
_range1.values = [[10]];
return context.sync()
.then(function () {
let _range2 = _sheet.getRange('B1');
_range2.values = [[20]];
let _rangepass = _sheet.getRange('A1').load("values");
return context.sync(_rangepass);
})
.then(function (_rangepassed) {
let _number3 = Number(_rangepassed.values) * 3;
let _range3 = _sheet.getRange('C1');
_range3.values = [[_number3]];
return context.sync()
});
}).catch(function (error) {
console.error(JSON.stringify(error));
});
Reference Chaining Syntax
This second chaining layout only requires you to have one return statement.
When you use this layout it is easy to quickly see how many times you are calling 'context.sync'.
return context.sync()
.then(function () {
.then(context.sync)
.then(function () {
.then(context.sync)
Example - Reference Chaining Syntax
This writes data to cell "A1", writes data to cell "B1", retrieves the value from cell "A1" and writes data to cell "C1".
Excel.run(function (context) {
let _workbook = context.workbook;
let _sheet = _workbook.worksheets.add();
let _range1 = _sheet.getRange("A1");
_range1.values = [[10]];
return context.sync()
.then(function () {
let _range2 = _sheet.getRange("B1");
_range2.values = [[20]];
})
.then(context.sync)
.then(function () {
let _range2 = _sheet.getRange("C1");
_range2.values = [[30]];
})
.then(context.sync);
}).catch(function (error) {
console.error(JSON.stringify(error));
});
© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext