# Single-Threaded thus Asynchronous

## Multi-thread vs mono-thread

In a synchronous, multi-threaded and data-driven world, this works:

```javascript
function processRequest(request) {
​
    /*
     * Pre-processing.
     */
    var query = prepareQuery(...);
​
    var result = execQuery(query); // might take few seconds...
​
    /*
     * Post-processing.
     */
    var response = createResponse(result);
​
    return response;
​
}
```

... but in a single-threaded world, this can lead to trouble as the application would freeze until it receives a response.

**Until the function ends&#x20;*****(and its callees)*****, no other function can be executed simultaneously.**

## Asynchronous processing using callbacks

```typescript
function processRequest(request, callback) {
​
    /*
     * Pre-processing.
     */
    var query = prepareQuery(...);
​
    execQuery(query, function (result) {
​
        /*
         * Post-processing.
         */
        var response = createResponse(result);
​
        callback(response);
​
    });
​
}
```

## Asynchronous processing advantages

* No threads count limitation.
* No memory overhead due to threads.
* No locks or semaphores.
* No greedy locks.
* No deadlocks.
* Data doesn't change during the execution of a function.

## Closures

A **closure** is the combination of a function definition and the lexical environment in which the latter is defined.

Closures determine the scope of the variables.

Variables can be read and modified in the closure where they are declared **but also in the functions defined inside**.

```javascript
function main() {
​
    var userName = 'Foo';
​
    function setUserName(value) {
        userName = value;
    }
​
    function getUserName() {
        return userName;
    }
​
    setUserName('John');
​
    console.log(getUserName()); // 'John';
​
}
​
main();
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://web-dev-guide.wishtack.io/ecmascript/single-threaded-thus-asynchronous.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
