October 22, 2024
Chicago 12, Melborne City, USA
javascript

How to wait for function call in Javascript without calling it directly


you can use Promises. In your case, you can modify your First and Second functions to return Promises. This way, you can await the completion of Second without having to call it directly.

like this

function First() {
  console.log('First is called');
  return new Promise(resolve => {
    setTimeout(() => {
      Second();
      resolve(); // Resolve the promise after Second is called
    }, 1000);
  });
}

function Second() {
  console.log('Second is called');
}

async function Main() {
  await First(); // Wait for First to complete
  console.log('I called First and I want that Second also is complete');
}

Main();

If you have a long chain of asynchronous functions where each function calls the next, you can still use Promises effectively.

function First() {
  console.log('First is called');

  return new Promise((resolve) => {
    setTimeout(() => {
      Second().then(resolve); // Call Second and wait for it to resolve
    }, 1000);
  });
}

function Second() {
  console.log('Second is called');

  return new Promise((resolve) => {
    setTimeout(() => {
      Third().then(resolve); // Call Third and wait for it to resolve
    }, 1000);
  });
}

function Third() {
  console.log('Third is called');

  return new Promise((resolve) => {
    setTimeout(() => {
      LastFunction().then(resolve); // Call LastFunction and wait for it to resolve
    }, 1000);
  });
}

function LastFunction() {
  console.log('Last function is called');

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(); // Resolve when the last function is done
    }, 1000);
  });
}

async function Main() {
  await First(); // Wait for the entire chain to complete
  console.log('All functions are complete');
}

// Call Main to start the process
Main();

if this is what do you mean by catching the last one



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video