简体   繁体   English

在promise函数中使用api调用

[英]Using api calls in promise function

I'm not fully understanding how promises work. 我没有完全理解诺言如何运作。 I made a function that executes an api call that uses a promise. 我做了一个函数,该函数执行使用promise的api调用。

function getSomeData(email, password) {
    axios.post('SomeURL/login', {
    email: email,
    password: password
  })
}

Whenever this function fires i can get the data that i want. 每当此函数触发时,我都可以获得所需的数据。 But whenever an error occurs the error will show up within the .then() call rather then the .catch() 但每当发生错误,错误将在中显示出来.then()调用甚则.catch()

getSomeData().then(data => {
  console.log(data)
}) 

How can i make sure that, when i call .catch() it will show my error there instead of in the .then() 我怎样才能确保,当我打电话.catch()就会有显示我的错误,而不是在.then()

You need to return the promise like this: 您需要像这样返回承诺:

function getSomeData(email, password) {
    return axios.post('SomeURL/login', {
        email: email,
        password: password
    })
}

Then it should be working (if the axios.post call returns promise). 然后它应该可以工作(如果axios.post调用返回promise)。

You can use an if statement to handle business logic errors. 您可以使用if语句来处理业务逻辑错误。 Then the catch error will handle server errors. 然后catch错误将处理服务器错误。

function getSomeData(email, password) {

  return axios.post('SomeURL/login', {
    email: email,
    password: password
  })
  .then(response => {
    if (response.statusText === 'OK') {
      // LOGIN SUCCESS
      // Do something with the login result
    } else {
      // LOGIN FAILURE, but not server failure
      // Redirect to login page, and give a message
    }
  })
  .catch(error => {
    console.log(error)
  // API is down
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM