Return promise in javascript es6

Let's say I have a file that imports a function from api and does something with the result.

import api from './api'

const getData = () => {
  api.get(url)
    .then(res => console.log(res))
    .catch(err => console.log(err))
}

I saw two different styles for returning the answer, so the error is bubbling.

version 1:

get: (url) => {
  return new Promise((resolve, reject) => axios.get(url)
    .then(res => resolve(res))
    .catch(err => reject(err)) )
}

version 2:

get: (url) => {
  return axios.get(url)
    .then(res => {
      if (res.success == 200) {
        return Promise.resolve(res)
      }
      return Promise.reject(res)
    })
}

What is the difference between these two approaches? Is there a preferred / best error handling method?

+4
source share
2 answers

In general, there are two convenient rules:

  • If your starting point is a promise (return value axios.get), then use new Promiseis an anti-pattern. thenand catchalready create new promises.

  • , ( , , , , , ).

, Version 2, Version 1.

1 : ; undefined. , - , ( ) then catch. , ( ) undefined.

2 -: res.success. Promise.resolve, :

get: (url) => axios.get(url).then(res => {
  if (res.success == 200) {
    return res;
  }
  return Promise.reject(res); // Or see note below
})

— — , Error, Promise.reject, . :

get: (url) => axios.get(url).then(res => {
  if (res.success == 200) {
    return res;
  }
  throw new Error(res/*...or something else useful here...*/);
})
+2

, Promise.

axios.get, , Promise, .

Promise, , , , . - :

get: (url) => {
  return new Promise((resolve, reject) => axios.get(url)
    .then(res => resolve(res))
    .catch(err => resolve(err)) )
}

.

0

Source: https://habr.com/ru/post/1684685/


All Articles