# Promises

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It is one way to solve callback hell.

A promise is a returned object to which you attach callbacks instead of passing callbacks into a function.

# How to make a Promise

const willGetYouADog = new Promise((resolve, reject) => {
})
1
2

image-20210123234027766

status is "pending" by default.

const willGetYouADog = new Promise((resolve, reject) => {
	reject()
})
1
2
3

image-20210123234132318

const willGetYouADog = new Promise((resolve, reject) => {
	resolve()
})
1
2
3

image-20210123234151439

.then will run if status is resolved

.catch will run if status is rejected

const willGetYouADog = new Promise((resolve, reject) => {
	resolve()
}).then(()=>{
  console.log("yes")
}).catch(()=>{
  console.log("no")
})
1
2
3
4
5
6
7

# Returning Promise from a Function

const makePromise = ()=>{
  return new Promise((resolve, reject) => {
	resolve()
})
    
makePromise()
  .then(()=>{
    console.log("yes")
  })
  .catch(()=>{
    console.log("no")
  })

1
2
3
4
5
6
7
8
9
10
11
12
13

# Resolving/Rejecting with Value

  1. Without Value
const fakeRequest = (url) => {
  return new Promise((resolve, reject) => {
    const rand = Math.random()
    if(rand<0.3){
      reject();
    }
    else{
      resolve()
    }
  })
}

fakeRequest()
.then(()=>{
  console.log("good")
})
.catch(()=>{
  console.log('baad')
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  1. With Value
const fakeRequest = (url) => {
  return new Promise((resolve, reject) => {
    const rand = Math.random()
    if(rand<0.3){
      reject({status:404});
    }
    else{
      const pages = {
        '/users': [
          {id:1, username:'ki'}
        ],
        '/about':"about page"
      };
      const data = pages[url]
      resolve({status:200, data})
    }
  })
}

fakeRequest('/users')
.then(()=>{
  console.log(res.status) //200
  console.log(res.data) //[id:1, username:'ki']
  console.log("good")
})
.catch((res)=>{
  console.log(res.status)  //404
  console.log('baad')
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# Promise Chain


1

# Axios


1
Last Updated: 3/1/2021, 9:19:08 PM