How to get data returned from fetch() promise?

后端 未结 3 1035
再見小時候
再見小時候 2020-12-11 12:26

I am having trouble wrapping my head around returning json data from a fetch() call in one function, and storing that result in a variable inside of another function. Here i

3条回答
  •  悲&欢浪女
    2020-12-11 12:55

    always return the promises too if you want it to work: - checkUserHosting should return a promise - in your case it return a promise which return the result data.

    function checkUserHosting(hostEmail, callback) {
        return fetch('http://localhost:3001/activities/' + hostEmail)
            .then((response) => { 
                return response.json().then((data) => {
                    console.log(data);
                    return data;
                }).catch((err) => {
                    console.log(err);
                }) 
            });
    }
    

    and capture it inside .then() in your main code:

    function getActivity() {
        let jsonData;
        activitiesActions.checkUserHosting(theEmail).then((data) => {
           jsonData = data;
        }        
    }
    

    EDIT:

    Or even better, use the new syntax as @Senthil Balaji suggested:

    const checkUserHosting = async (hostEmail, callback) => {
     let hostEmailData  = await fetch(`http://localhost:3001/activities/${hostEmail}`)
     //use string literals
     let hostEmailJson = await hostEmailData.json();
     return hostEmailJson;
    }
    
    const getActivity = async () => {
     let jsonData = await activitiesActions.checkUserHosting(theEmail);
      //now you can directly use jsonData
    }
    

提交回复
热议问题