How to get data returned from fetch() promise?

后端 未结 3 1024
再見小時候
再見小時候 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:52

    You can make use of new ES6 and Es7 syntax and what others have written is also correct, but this can be more readable and clean,

    you are trying to get aysnc value synchronously, here jsonData will be undefined because, you move to next line of execution before async function(checkUserHosting) is finish executing, this can be written as follows

    const getActivity = async () => {
     let jsonData = await activitiesActions.checkUserHosting(theEmail);
      //now you can directly use jsonData
    }
    

    and you can write checkUserHosting in a different using new syntax like this

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

提交回复
热议问题