Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

javascript - How to get data returned from fetch() promise?

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 is where I am making the fetch() call to my API:

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

And this is how I am trying to get the returned result:

function getActivity() {
    jsonData = activitiesActions.checkUserHosting(theEmail)
}

However, jsonData is always undefined here (which I am assuming is because the async fetch call has not finished yet when attempting to assign the returned value to jsonData. How do I wait long enough for the data to be returned from the fetch call so that I can properly store it inside of jsonData?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...