---
# System prepended metadata

title: Typescript - Promise
tags: [web dev, learn, typescript]

---

# Typescript - Promise


## Assign a value to a variable that is defined outside of Promise

### Use `Promise.then`
```
function getPromiseNums(): Promise<number[]> {
  return Promise.resolve([1, 2, 3, 4, 5]);
}


function disPlayNums(): void {
  let len = 0;

  getPromiseNums()
    .then((blocks) => {
      // console.log(blocks[0]);
      
      len = blocks.length;
    })
    .then(() => {
      console.log(len);
    })
    .then(() => {
      for (let i = 0; i < len; i += 1) {
        getPromiseNums().then((blocks) => {
          console.log(blocks[i]);
        });
      }
    });
}

disPlayNums();

```



### Use `new Promise`
Resource
https://www.freecodecamp.org/news/javascript-promise-tutorial-how-to-resolve-or-reject-promises-in-js/

My Example:

```
let responseStr = '';
  const request = require('request');
  const promise = new Promise(function (resolve, reject) {
    request(options, async (error: string, response) => {
      resolve(response);
    });
  });

  await promise.then((response) => {
    responseStr = JSON.stringify(response);
  });
```










###### tags: `typescript` `learn` `web dev`