[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/vlott4444/JavaScript/main/tutorials/fetch/README.md [Back]  [Original]

#   promise  fetch,   .

## 
   2- : 

-             API:      XMLHttpRequest,   -   `fetch`.           ,
      API,
       ,
    .

-          :  ""   ( 3)    ,       ( 4)            CORS.

## 

 1:
1.   `Promise`.
2.  `Promise`.
3.   `async await`  JS.
4.   `fetch`   .

 2:
1.     `Vite`.
2.     .

##  1.

### 1.   `Promise`
 ,    `promises` (),          `fetch`?
  ,  fetch    ,  ,   `promise`.

     ,   fetch    ,   .

*Promise* -   ,         .
()    ?  ,       ,   :

    - ,    ,   .  -       ,
      ( )   ,
   ,          - .
   -   ,   -    ,     .     ?
![ 3](./assets/client-server-timings.jpg)
        3  ,  
  -  -,     ,   2       ,      3 .
   8    .

      ,   .    ,   , 
     ,   
     ,              ,
      ,     .
  !       -  "".

 -  ,  ,      ,   .
   3 ,     :
1. Pending - ,   ,  ,     
2. Fulfilled -   ,  
3. Rejected -  ,  -      

    :
```ts
new Promise((resolve, reject) => {
    //...      , ,     
    //...  pending -> fulfilled   pending -> rejected
    
    // resolve - ,        pending -> fulfilled
    resolve() //    ""      ,     fulfilled
    
    // reject - - ,        pending -> rejected
    reject() //    ""  ,   ",  ".       rejected
    
})
```

 : ",     ,      ?
 ,    pending,   fulfilled,     ?"

       ( -   ):

1. `then()`
     
```ts
// promise -  
promise.then(
  function(result) { /*    */ },
  function(error) { /*   */ }
);
```
 `then()`   ,       ,   .    ,    ,     
 , `then`  ,      pending -> fulfilled.

2. `catch()`
 ,      ,      .    ,       `then`
 , 
```ts
//     
promise.then(null, (error) => {console.log(error)})
```
  ,   
```ts
//     
promise.catch((error) => {console.log(error)})
```

3. `finally()`
    ,       - . ,          .


### 2.  `Promise`
   ,        :

```ts
const promise = new Promise((resolve, reject) => {
    //    
    const randNumber = Math.random() * 100; // return number from 0 to 100
    
    //  ,         10 
    setTimeout(() => {
        //   ,     20 ,      fulfilled,   rejected
        if (randNumber > 20) {
            resolve();
        } else {
            reject();
        }
    }, 10000);
})
```
 ,     `pending` - 10 ,       (`funlfilled`)   80     (`rejected`).

          :

```ts
promise
    .then(() => {console.log('')}) //     
    .catch(() => {console.log(' ')}) //    
    .finally(() => {console.log('')}) //     
```

### 3.   `async await`  JS
       ""  then  catch.       .
   JS   `async await`.  " " ,   .
 :

```ts
const getDataFromServer = () => {
    return new Promise((resolve, reject) => {
        //    
        const randNumber = Math.random() * 100; // return number from 0 to 100

        //  ,         10 
        setTimeout(() => {
            //   ,     20 ,      fulfilled,   rejected
            if (randNumber > 20) {
                resolve('');
            } else {
                reject('!');
            }
        }, 10000);
    }).then(result => console.log(result))
        .catch(console.log)
}
```

     :
```ts
const getDataFromServer = async () => {
    //  then  catch    try {} catch {}
    try {
        
        const result = await new Promise((resolve, reject) => {
            //    
            const randNumber = Math.random() * 100; // return number from 0 to 100

            //  ,         10 
            setTimeout(() => {
                //   ,     20 ,      fulfilled,   rejected
                if (randNumber > 20) {
                    resolve('');
                } else {
                    reject('!');
                }
            }, 10000);
        });
        //        ,      ,  
        console.log(result);
    } catch (err) {
        console.log(err);
    }
}
```

### 4.   `fetch`   
`fetch` -      ,    . [ ](https://learn.javascript.ru/fetch)

          ? 
   ,   XMLHttpRequest,         .
   :
```ts
    let xhr = new XMLHttpRequest()
    xhr.onload = () => {
        //... - ,   
    }
    
    xhr.onerror = () => {
        // ...  ,       
        //  ,       .
    }
    
    xhr.open('POST', getUrl(url))
    xhr.send();
```
  XMLHttpRequest   ,           .
       onLoad,        onError.
   ,     .

 ,      

```ts
    const getDataFromServer = async () => {
       try { 
           // GET    
           const result = await fetch('yandex.ru');
           
           //     
           return result;
       } catch (e) {
           console.log(e);
       }
}
```
##  2

### 1.     `Vite`.

[Vite ](https://vite.dev/) -       . [](https://vite.dev/guide/#manual-installation) `vite`       ( 3).

1.     :

```bash
cd your-lab3-folder
```

2.  `vite`:

```bash
npm install -D vite
```

3.    `package.json`:

```json
// package.json
{
    "scripts": {
        "dev": "vite", // start dev server, aliases: `vite dev`, `vite serve`
        "build": "vite build", // build for production
        "preview": "vite preview" // locally preview production build
    }
}
```

4.  `vite.config.js`:

```js
// vite.config.js
export default {
    build: {
        outDir: './public',
        emptyOutDir: true,
    },
};
```

!

 `npm run dev`    `http://localhost:5173/`,  ,    (    ).
![Dev](assets/dev.png)

 `npm run build`, ,    `public`    :
![alt text](assets/build-public.png)

    ,   `npm run preview`.       production-,     `public`.

Dev- (  `vite` - ` npm run dev`  vs-code `live-server`):
![Before structure](assets/before-structure-dev.png)

Preview- (  `vite` - `npm run preview`):
![alt text](assets/after-structure-public.png)

## 2.     .

    `http://localhost:3000/`,        ,  :
![Not found](assets/not-found.png)

           :

1.    `public`    :
   ![Public in backend](assets/public-in-backend.png)

2.    NestJS ,     `public`   :

```ts
// main.ts
...
import { NestExpressApplication } from '@nestjs/platform-express';
import { resolve } from 'path';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useStaticAssets(resolve(__dirname, '..', 'public'));

  await app.listen(process.env.PORT ?? 3000);
}

...
```

-   `app.useStaticAssets(resolve(__dirname, '..', 'public'));` -     

-       `NestExpressApplication`    ,  ts ,       `express` (`useStaticAssets`    express-)

!

  NestJS     `http://localhost:3000/`,  ,     ,        CORS,       .
![Frontend and backend](assets/frontend-and-backend.png)

       4:
![Final backend](assets/final-backend.png)

##  

     .    ,       
XMLHttpRequest  fetch.

Web Proxy Viewer  |  New URL  |  Original Page