context.sync

The more calls you make to this method the slower your code will run.
You should only call this method when you absolutely have to.
The sync() method available on the request context synchronizes the state between the JavaScript proxy objects and real objects in Office application.
This method can be used to execute the instructions that have been added to the queue.
This method can be used to retrieve properties from the loaded Office objects.
This method returns a promise, which is resolved when synchronization is complete.
You call a context.sync to indicate the completion of interacting with the Office application.
You call a context.sync when you are waiting to get the result back from an object.load.
Helper functions never call context.sync.


Nested Syntax

return context.sync() 
   .then(function () {
      return context.sync()
         .then(function () {

Example 1

This writes data to cell "A1".

Excel.run(function (context) { 
  let _workbook = context.workbook;
  let _sheet = _workbook.worksheets.add();
  let _range1 = _sheet.getRange('A1');
  _range1.values = [[10]];
  return context.sync();
})
.catch(function (error) {
    console.error(JSON.stringify(error));
});

Example 2

This writes data to cell "A1", writes data to cell "B1" and then retrieves the value from cell "A1".

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()
        .catch(function (error) {
          console.error(JSON.stringify(error));
        });
    })
    .catch(function (error) {
       console.error(JSON.stringify(error));
    });
})
.catch(function (error) {
  console.error(JSON.stringify(error));
});

Example 3

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

© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext