【问题标题】:React Class how to return a Boolean after a promise fetch callReact Class如何在promise fetch调用后返回布尔值
【发布时间】:2019-08-19 16:07:42
【问题描述】:

你好我有这个类,当我从另一个组件调用 Auth.isAuthenticated() 时,它总是返回 false(它的默认值),即使服务器返回 200 响应,女巫设置 this.authenticated = true 。 如何使用 promise 让方法等到 fetch 调用完成然后返回结果

编辑: 我需要返回布尔值真或假,因此基于此,我可以显示或隐藏组件,所有答案都有帮助,但我需要布尔值而不是承诺任何帮助

    class Auth {
    constructor() {
        this.authenticated = false;
    }


    isAuthenticated() {
        //get token from local storage if there is one
        const jwttoken = localStorage.getItem('jwttoken');
        const bearer = 'Bearer ' + jwttoken;
        const data = new FormData();
        // get the website backend main url from .env
        const REACT_APP_URL = process.env.REACT_APP_URL
        fetch(`${REACT_APP_URL}/api/auth/verify`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Authorization': bearer,
            },
            body: data
        }).then(
            (response) => {
                response.json()
                    .then((res) => {
                        if (response.status === 200) {
                            this.authenticated = true;
                        }
                        if (response.status === 401) {
                            localStorage.removeItem('jwttoken');
                            this.authenticated = false;
                        }
                    })
            }
        ).catch((err) => {
            // console.log(err)
        });

        return this.authenticated;
    }


}



export default new Auth();

我从另一个组件调用 Auth.isAuthenticated() === true

export const PrivateRoute = ({ component: Component, ...rest }) => {

  return (
    <Route {...rest} render={(props) => (
      Auth.isAuthenticated() === true
        ? <Component {...props} />
        : <Redirect to='/admin' />
    )} />
      )
}

【问题讨论】:

    标签: javascript reactjs es6-promise


    【解决方案1】:

    假设您要编写一个函数,该函数返回一个承诺并在某些操作完成时解析(例如 API 调用)。你可以这样写:

    const myAsyncFunction = () =>{
        return new Promise((resolve, reject) =>{
            //Faking an API Call
            setTimeout(() => resolve('data'), 400)
        })
    }
    

    给你!现在你有一个函数可以返回一个承诺,该承诺将在 400 毫秒内解决。现在您需要使用.then() 方法或async await 语句。

    const sideEffects = async () =>{
        const result = await myAsyncFunction()
        console.log(result) //'data'
    }
    

    【讨论】:

      【解决方案2】:

      如果你不想做async/await,你可以让isAuthenticated返回一个承诺。

      isAuthenticated() {
        return new Promise((resolve, reject) => {
          //get token from local storage if there is one
              const jwttoken = localStorage.getItem('jwttoken');
              const bearer = 'Bearer ' + jwttoken;
              const data = new FormData();
              // get the website backend main url from .env
              const REACT_APP_URL = process.env.REACT_APP_URL
              fetch(`${REACT_APP_URL}/api/auth/verify`, {
                  method: 'POST',
                  headers: {
                      'Accept': 'application/json',
                      'Authorization': bearer,
                  },
                  body: data
              }).then(
                  (response) => {
                      response.json()
                          .then((res) => {
                              if (response.status === 200) {
                                  resolve(true)
                              }
                              if (response.status === 401) {
                                  localStorage.removeItem('jwttoken');
                                  resolve(false)
                              }
                          })
                  }
              ).catch((err) => {
                  // reject(err)
              });
        })        
      }
      

      在异步函数内部你可以使用let isAuthenticated = await isAuthenticated() 或者你可以在异步函数外部使用.then.catch 来返回结果

      【讨论】:

        【解决方案3】:

        使用等待异步

        async isAuthenticated() {
                //get token from local storage if there is one
                const jwttoken = localStorage.getItem('jwttoken');
                const bearer = 'Bearer ' + jwttoken;
                const data = new FormData();
                // get the website backend main url from .env
                const REACT_APP_URL = process.env.REACT_APP_URL
                const response = await fetch(`${REACT_APP_URL}/api/auth/verify`, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Authorization': bearer,
                    },
                    body: data
                });
        
                const responseToJson = await response.json();
        
                 if (responseToJson.status === 200) {
                     this.authenticated = true;
                 }
                 if (responseToJson.status === 401) {
                     localStorage.removeItem('jwttoken');
                     this.authenticated = false;
                 }
        
               return this.authenticated;
            }
        
        

        【讨论】:

        • @Alexander 谢谢你,但我得到了一个承诺,但我需要一个布尔值
        • @Rida 我的情况是你应该得到一个布尔值,而不是一个 Promise
        • @AlexandrZavalii 它仍然会返回一个承诺
        猜你喜欢
        • 2017-09-05
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2019-11-03
        • 1970-01-01
        • 2017-06-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多