context.sync - async/await

This is a new way of writing asynchronous code and was added in ES 2017 and TypeScript 2.1
This is built on top of promises.
This approach means your asynchronous code looks more like synchronous code.

await context.sync(); 
await context.sync();
await context.sync();

Example 1

This writes data to cell "A1".

Excel.run(async (context) => { 
  let _workbook = context.workbook;
  let _sheet = _workbook.worksheets.add();
  let _range1 = _sheet.getRange('A1');
  _range1.values = [[10]];
  await context.sync();

}).catch((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(async (context) => { 
  let _workbook = context.workbook;
  let _sheet = _workbook.worksheets.add();
  let _range1 = _sheet.getRange('A1');
  _range1.values = [[10]];
  await context.sync();

  let _range2 = _sheet.getRange('B1');
  _range2.values = [[20]];
  let _rangepass = _sheet.getRange('A1').load("values");
  await context.sync();

}).catch((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(async (context) => { 
  let _workbook = context.workbook;
  let _sheet = _workbook.worksheets.add();
  let _range1 = _sheet.getRange('A1');
  _range1.values = [[10]];
  await context.sync();

  let _range2 = _sheet.getRange('B1');
  _range2.values = [[20]];
  let _rangepass = _sheet.getRange('A1').load("values");
  await context.sync();

  let _number3 = Number(_rangepass.values) * 3;
  let _range3 = _sheet.getRange('C1');
  _range3.values = [[_number3]];
  await context.sync();

}).catch((error) => {
    console.error(JSON.stringify(error));
});

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