-1

As the title suggests, I want to build a function that calls the other functions one after the other. Unfortunately, the functions take different lengths of time and understandably problems arise when they are executed.

Is there a simple solution to this problem?

function allInOne() {
  loadData();
  moveSheet();
  sortStockData();
}

Before the first function is finished, the second has already been carried out. But it should all be done one after the other. I just got stuck through google etc.

Thank you in advance.

Peter
  • 79
  • 8
  • you should try this solution by jakub, see if it helps [Proper way to wait for one function to finish before continuing](https://stackoverflow.com/a/55698897/12974099) – Sudeep Kuchara Jan 17 '21 at 20:29
  • Ending functions when sequentially https://stackoverflow.com/a/41177481/7215091 – Cooper Jan 17 '21 at 21:23

1 Answers1

2

Look inside the functions, as they may be returning promises

Normal Javascript is single-threaded, so when you call one function and then another and another (as you did) you can expect them to run in sequence.

However you will probably find that loadData() is an asynchronous function, returning a Promise. Look at its return statement to check this.

If it is returning a promise, you can say,

loadData().then(result => moveSheet())

If moveSheet too, returns a promise, you can expand the chain as follows:

loadData().then(result => moveSheet()).then(result => sortStockData())

Another way to express this is with the 'await' keyword

async function x(){
  await loadData();
  await moveSheet();
  sortStockData();
}

More information on Promises is here.

https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26