如何获取从 fetch() 承诺返回的数据? [英] How to get data returned from fetch() promise?

查看:231
本文介绍了如何获取从 fetch() 承诺返回的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从一个函数中的 fetch() 调用返回 json 数据,并将该结果存储在另一个函数中的变量中.这是我对 API 进行 fetch() 调用的地方:

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

但是,jsonData 总是 undefined 在这里(我假设这是因为尝试将返回的值分配给 时异步提取调用尚未完成jsonData.如何等待足够长的时间让数据从 fetch 调用中返回,以便我可以将其正确存储在 jsonData 中?

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?

推荐答案

总是 return 承诺,如果你想让它工作:- checkUserHosting 应该返回一个承诺- 在你的情况下,它 return 一个 promise return 结果 data.

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

并在主代码中的 .then() 中捕获它:

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

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

或者更好的是,使用@Senthil Balaji 建议的新语法:

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
}

这篇关于如何获取从 fetch() 承诺返回的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆