简体   繁体   English

JavaScript函数执行顺序

[英]JavaScript Function Execution Order

Say you have the following three functions and variable 假设您具有以下三个功能和变量

var someList = [];

makeObject() {

 // loops through someList here to create an object
 // then calls sendObject function

sendObject()

}

sendObject() {
 // sends object to database using HTTP call
}

resetList() {
 // resets the list to be empty
 // e.g. someList = []
}

Then you call them like so 然后你这样称呼他们

makeObject()
resetList()

Is there any possiblity or any situation that the list will be reset before the makeObject function has a chance to loop through it? 在makeObject函数有机会循环通过列表之前,是否有可能或将列表重置的任何情况?

There are plenty of things you can do in JavaScript which are asynchronous and non-blocking ( XMLHttpRequest and setTimeout are classic examples). 您可以在JavaScript中执行很多异步和非阻塞的操作( XMLHttpRequestsetTimeout是经典示例)。 If you use any of those inside makeObject then resetList will run before the asynchronous parts get called. 如果您在makeObject内部使用任何这些方法,则resetList将在调用异步部分之前运行。

resetList() will be called directly after the HTTP call is made. 将在进行HTTP调用后直接调用resetList()。 Unless you do other async work before the HTTP call, the order will always be: 除非您在HTTP调用之前进行其他异步工作,否则顺序始终为:

  • makeObject() makeObject()
  • loop inside makeObject() 在makeObject()内部循环
  • sendObject() is called from inside makeObject() 从makeObject()内部调用sendObject()
  • sendObject() does the HTTP call sendObject()执行HTTP调用
  • resetList() gets triggered right after the HTTP call since that HTTP call is async. 由于HTTP调用是异步的,因此在HTTP调用后立即触发resetList()。
  • The HTTP returns and any handlers attached to it are triggered. HTTP返回,并触发附加到它的所有处理程序。

But make sure that you don't do any other async work, else this will not apply. 但是请确保您没有执行任何其他异步工作,否则这将不适用。

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

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