如何访问异步函数 (javascript/react) 中 for-in 循环内的变量?
How to access variable inside a for-in loop within an async function (javascript/react)?
所以我在 React 项目中创建了这个小的 fetch 函数来循环返回的对象并给我一些东西。
我正在尝试取回 的值profileCount 在异步函数之外访问它。
我该怎么做?
useEffect(() => {
async function getProfiles() {
try {
const url = '';
let h = new Headers();
h.append('Accept', 'application/json');
let encoded = window.btoa('superuser:superuser');
let auth = 'Basic ' + encoded;
h.append('Authorization', auth);
const response = await fetch(url, {
method: 'GET',
mode: 'cors',
headers: h,
credentials: 'same-origin',
});
const data = await response.json();
let results = data.results;
let profileCount = 0;
for (let key in results) {
let innerObject = results[key];
for (let newKey in innerObject) {
if (innerObject[newKey].indexOf('pages/ProfilePage') > -1) {
profileCount += 1;
return profileCount;
}
}
}
} catch (err) {
console.log('test' + err);
}
}
getProfiles();
}, []);
您的代码很好,只需将 return
语句移到 for
之后。
for (let key in results) {
let innerObject = results[key];
for (let newKey in innerObject) {
if (innerObject[newKey].indexOf('pages/ProfilePage') > -1) {
profileCount += 1;
}
}
}
return profileCount;
工作流程如下,
useEffect(async () => {
async function getProfiles() {}
const count = await getProfiles();
}, []);
但您可能必须这样做以避免警告,
useEffect(() => {
(async () => {
let response = await fetch('api/data')
})();
}, [])
所以我在 React 项目中创建了这个小的 fetch 函数来循环返回的对象并给我一些东西。
我正在尝试取回 的值profileCount 在异步函数之外访问它。
我该怎么做?
useEffect(() => {
async function getProfiles() {
try {
const url = '';
let h = new Headers();
h.append('Accept', 'application/json');
let encoded = window.btoa('superuser:superuser');
let auth = 'Basic ' + encoded;
h.append('Authorization', auth);
const response = await fetch(url, {
method: 'GET',
mode: 'cors',
headers: h,
credentials: 'same-origin',
});
const data = await response.json();
let results = data.results;
let profileCount = 0;
for (let key in results) {
let innerObject = results[key];
for (let newKey in innerObject) {
if (innerObject[newKey].indexOf('pages/ProfilePage') > -1) {
profileCount += 1;
return profileCount;
}
}
}
} catch (err) {
console.log('test' + err);
}
}
getProfiles();
}, []);
您的代码很好,只需将 return
语句移到 for
之后。
for (let key in results) {
let innerObject = results[key];
for (let newKey in innerObject) {
if (innerObject[newKey].indexOf('pages/ProfilePage') > -1) {
profileCount += 1;
}
}
}
return profileCount;
工作流程如下,
useEffect(async () => {
async function getProfiles() {}
const count = await getProfiles();
}, []);
但您可能必须这样做以避免警告,
useEffect(() => {
(async () => {
let response = await fetch('api/data')
})();
}, [])