how do i wait for a function to finish in javascript

To wait for a function to finish its operation in JavaScript, there are several ways.

  1. Using callback functions:
index.tsx
function myFunction(callback) {
  // Some operation
  callback();
}

myFunction(function() {
  console.log('Operation completed!');
});
136 chars
9 lines
  1. Using Promises:
index.tsx
function myFunction() {
  return new Promise((resolve, reject) => {
    // Some operation
    if (/* operation successful */) {
      resolve('Operation completed!');
    } else {
      reject('Operation failed!');
    }
  });
}

myFunction().then(result => {
  console.log(result);
}).catch(error => {
  console.error(error);
});
331 chars
17 lines
  1. Using async/await:
index.tsx
async function myFunction() {
  // Some operation
  let result = await someOtherFunction();
  return result;
}

myFunction().then(result => {
  console.log(result);
}).catch(error => {
  console.error(error);
});
213 chars
12 lines

Note that async/await works only inside an async function.

gistlibby LogSnag