React Class如何在promise获取调用后返回布尔值

时间:2019-03-28 19:08:12

标签: javascript reactjs es6-promise

您好,当我从react中的另一个组件调用Auth.isAuthenticated()时,我有了此类,它始终返回false(其默认值),即使服务器返回200响应,女巫也会设置this.authenticated = true。 我如何使用promises使方法等到fetch调用完成后再返回结果

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

    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' />
    )} />
      )
}

3 个答案:

答案 0 :(得分:3)

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

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

您去了!现在您有了一个返回诺言的函数,它将在400ms内解决。现在,您需要使用.then()方法或async await语句。

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

答案 1 :(得分:1)

如果您不想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返回结果

答案 2 :(得分:0)

使用等待异步

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;
    }