# Promises

A Promise may in one of three possible states.

1. pending
2. fulfilled
3. rejected

```javascript
EX: 
const promise = new Promise((resolve, reject) => {
    if (true) {
        resolve("Stuff worked");
    } else {
        reject("Error: Something went wrong");
    }
});

promise.then(res => console.log(res)); // Stuff worked

promise
    .then(res => res + '!')
    .then(res2 => console.log(res2)); // Stuff worked!

promise
    .then(res => res + '!')
    .then(res2 => {
        throw Error('Simple error');
        console.log(res2);
    })
    .catch((err) => console.log(err)); // Simple error
    
promise
    .then(res => res + '!')
    .then(res2 => {
        return res2 + '?';
    })
    .catch((err) => console.log(err))
    .then((res3) => console.log(res3)); // Stuff worked!?
```

catch is executed only when any error occurred. It will considers the error only it occurred before its placement.

```javascript
EX:
const promise = new Promise((resolve, reject) => {
    if (true) {
        resolve("Stuff worked");
    } else {
        reject("Error: Something went wrong");
    }
});

const promise2 = new Promise((resolve, reject) => {
    setTimeout(resolve, 100, 'HIII');
});

const promise3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 1000, 'PROOKIE');
});

const promise4 = new Promise((resolve, reject) => {
    setTimeout(resolve, 5000, 'It is me you are loking for me?');
});

Promise.all([promise, promise2, promise3, promise4])
    .then(values => console.log(values));
// ["Stuff worked", "HIII", "PROOKIE", "It is me you are loking for me?"]
```

Promise all takes multiple promises in array and result will be array of all the results of all promises.

The result will be received only after all the promises execution is completed. If any one of them gets error, all process will be stopped.


---

# 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://javascript-1.gitbook.io/javascript/promises.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.
