简体   繁体   English

主function依次调用其他函数

[英]Main function calls the other functions one after the other

As the title suggests, I want to build a function that calls the other functions one after the other.正如标题所示,我想构建一个 function 一个接一个地调用其他函数。 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.在第一个 function 完成之前,第二个已经完成。 But it should all be done one after the other.但这一切都应该一个接一个地完成。 I just got stuck through google etc.我刚刚被谷歌等困住了。

Thank you in advance.先感谢您。

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.正常的 Javascript 是单线程的,因此当您调用一个 function 然后另一个又一个(如您所做的那样)时,您可以期望它们按顺序运行。

However you will probably find that loadData() is an asynchronous function, returning a Promise .但是你可能会发现 loadData() 是一个异步的 function,返回一个Promise Look at its return statement to check this.查看它的return语句来检查这一点。

If it is returning a promise, you can say,如果它返回 promise,你可以说,

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

If moveSheet too, returns a promise, you can expand the chain as follows:如果moveSheet也是,返回一个 promise,你可以展开链如下:

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

Another way to express this is with the 'await' keyword另一种表达方式是使用'await'关键字

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

More information on Promises is here.更多关于 Promises 的信息在这里。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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