When is JavaScript synchronous?

前端 未结 7 2000
孤独总比滥情好
孤独总比滥情好 2020-11-22 03:48

I have been under the impression for that JavaScript was always asynchronous. However, I have learned that there are situations where it is not (ie DOM manipulations). Is

7条回答
  •  孤独总比滥情好
    2020-11-22 04:33

    "I have been under the impression for that JavaScript was always asynchronous"

    You can use JavaScript in a synchronous way, or an asynchronous way. In fact JavaScript has really good asynchronous support. For example I might have code that requires a database request. I can then run other code, not dependent on that request, while I wait for that request to complete. This asynchronous coding is supported with promises, async/await, etc. But if you don't need a nice way to handle long waits then just use JS synchronously.

    What do we mean by 'asynchronous'. Well it does not mean multi-threaded, but rather describes a non-dependent relationship. Check out this image from this popular answer:

             A-Start ------------------------------------------ A-End   
               | B-Start -----------------------------------------|--- B-End   
               |    |      C-Start ------------------- C-End      |      |   
               |    |       |                           |         |      |
               V    V       V                           V         V      V      
    1 thread->|<-A-|<--B---|<-C-|-A-|-C-|--A--|-B-|--C-->|---A---->|--B-->| 
    

    We see that a single threaded application can have async behavior. The work in function A is not dependent on function B completing, and so while function A began before function B, function A is able to complete at a later time and on the same thread.

    So, just because JavaScript executes one command at a time, on a single thread, it does not then follow that JavaScript can only be used as a synchronous language.

    "Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous"

    I'm wondering if this is the heart of your question. I take it that you mean how do you know if some code you are calling is async or sync. That is, will the rest of your code run off and do something while you wait for some result? Your first check should be the documentation for whichever library you are using. Node methods, for example, have clear names like readFileSync. If the documentation is no good there is a lot of help here on SO. EG:

    How to know if a function is async?

提交回复
热议问题