So what is asynchrony?

  • 0
    Hello. Could explain to me a newbie. How can a synchronous single-threaded language perform tasks asynchronously at all? Downloading files, writing - reading, processing data. How does it work at all?
    JavaScript Landen Walker, Dec 23, 2019

  • 3 Answers
  • 0
    So you yourself almost answered. The language is single-threaded, so each operation waits for the previous one to complete during synchronous programming. And it doesn't wait - with asynchronous. And to determine the completion of an asynchronous operation, Promises and Asinks were invented.

    This is me, of course, on the fingers. Academic answers about asynchrony are easy to Google.
    Clara Weeks

  • 0
    How can a synchronous single-threaded language perform tasks asynchronously at all?




    In reality, he performs them one by one, just the so-called. asynchronous operations, such as promises, are not executed in the general order of the written code, but are enqueued and executed after the synchronous operations are completed.



    For example

    function fetchMe() {
    fetch("/api/get").then(response => console.log("Сервер ответил " + response))
    console.log("Ждем ответа сервера")
    }




    The first line is asynchronous, it is not executed immediately but is queued. The second line is executed immediately.



    What fetch does is simply check regularly (in order of the event queue) to see if the server has responded, and when the server responded, the code in then is executed. Moreover, since js is synchronous, if there is some costly operation before receiving the server's response, fetch will wait patiently and you will receive an answer not when it actually came, but when the periodic check performed by the fetch function waits for its turn. This is asynchrony in js.
    Anonymous

  • 0

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!