简体   繁体   中英

How can I use async/await statements in nested functions?

There is a nested function where asnyc functions and normal functions are used. I am a beginner in JavaScript by the way.

async function run() {
  try {
    await Excel.run(async context => {
      document.getElementById("status").value = "";
      let checks = [];
      const sheet = context.workbook.worksheets.getActiveWorksheet();
      const uR = context.workbook.getSelectedRange();
      uR.load('values');
      await context.sync();
      let data2 =uR.values;
      let data2.forEach((row,index)=>{
      docfunction(row);

Within this docfunction I want to use:

   function docfunction(row) {
    let checknumber = context.workbook.functions.isNumber(row[5]);
    checknumber.load('value');
    await context.sync();
    checknumber = checknumber.value;

However, await context.sync() is not working.

you also need to make the docfunction async in order to make it work:

async function docfunction(row) {
let checknumber = context.workbook.functions.isNumber(row[5]);
checknumber.load('value');
await context.sync();
checknumber = checknumber.value;

then you need to call it with await keyword inside your run function:

await dysfunction(row);

You may be better served returning a list of Promises and using a for await of loop, but this should be what you are looking for.
You could make it work with a .forEach , but there is really no reason to as it does not make the code any more readable.

async function run() {
  try {
    await Excel.run(async context => {
      document.getElementById("status").value = "";
      let checks = [];
      const sheet = context.workbook.worksheets.getActiveWorksheet();
      const uR = context.workbook.getSelectedRange();
      uR.load('values');
      await context.sync();
      let data2 =uR.values;
      for(const [row,index] of data2.entries()) {
        await docfunction(row);

...

   async function docfunction(row) {
    let checknumber = context.workbook.functions.isNumber(row[5]);
    checknumber.load('value');
    await context.sync();
    checknumber = checknumber.value;

await expect a promise, Here is dummy code for async/await.

async function run() {
    // It will wait for the promise to resolve
    await new Promise((resolve) => {
        setTimeout(() => {
            resolve(console.log('Inside promise'));
        }, 3000);
    });
    // when promise gets resolved it will print
    console.log('Outside Promise');
}

run();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM