Sur*_*ero 4 javascript react-native
我在从一个函数中的 fetch() 调用返回 json 数据并将该结果存储在另一个函数内的变量中时遇到了麻烦。这是我对 API 进行 fetch() 调用的地方:
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);
})
});
}
Run Code Online (Sandbox Code Playgroud)
这就是我试图获得返回结果的方式:
function getActivity() {
jsonData = activitiesActions.checkUserHosting(theEmail)
}
Run Code Online (Sandbox Code Playgroud)
但是,jsonData
总是undefined
在这里(我假设这是因为在尝试将返回的值分配给jsonData
.将其存储在jsonData
?
永远return
的承诺太多,如果你想让它工作: -checkUserHosting
应返回一个承诺-在你的情况下,它return
一个promise
它return
的结果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);
})
});
}
Run Code Online (Sandbox Code Playgroud)
并在主代码中的 .then() 中捕获它:
function getActivity() {
let jsonData;
activitiesActions.checkUserHosting(theEmail).then((data) => {
jsonData = data;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
或者甚至更好,使用@Senthil Balaji 建议的新语法:
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
}
Run Code Online (Sandbox Code Playgroud)
你说对了一部分。这是因为您试图以同步方式获取此异步调用的结果。做到这一点的唯一方法与处理任何其他承诺的方式相同。通过.then
回调。所以对于你的片段:
function getActivity() {
return activitiesActions.checkUserHosting(theEmail).then((jsonData) => {
// Do things with jsonData
})
}
Run Code Online (Sandbox Code Playgroud)
任何依赖于异步操作的函数本身都必须变为异步。.then
因此,对于任何需要使用该函数的事物,都不可避免地要使用checkUserHosting
。
归档时间: |
|
查看次数: |
16675 次 |
最近记录: |