[英]I can’t seem to find where I did or did not use the await keyword right
我已經連續兩天被竊聽,試圖弄清楚我在哪里搞砸了,但我無法接受這是我編寫的代碼的完整細分
useEffect(() => {
const main = async () => {
const profileData = [];
try {
coll.map(async (col) => {
const instance = new Contract(col, nftABI, provider);
const balance = await instance.balanceOf(profile);
let profileBalance = balance.toNumber();
const tokenIds = [];
const name = [];
const images = [];
for (let i = 0; i < profileBalance; i++) {
if (profileBalance > 0) {
console.log(profileBalance, i, col);
const tokenId = await instance.tokenOfOwnerByIndex(profile, i);
let NumTokenId = tokenId.toNumber();
let StrTokenId = String(NumTokenId);
const uri = await instance.tokenURI(StrTokenId);
const url = uri.replace(
"ipfs://",
"https://gateway.pinata.cloud/ipfs/"
);
const ipfsFile = await fetch(url).then((r) => r.json());
const imageUri = ipfsFile.image.replace(
"ipfs://",
"https://gateway.pinata.cloud/ipfs/"
);
name.push(ipfsFile.name);
images.push(imageUri);
tokenIds.push(StrTokenId);
}
}
const obj = {
collection: col,
tokenArray: tokenIds,
image: images,
name: name,
};
if (obj.name.length > 0) {
profileData.push(obj);
}
});
} catch (error) {
console.log(error);
}
setR(profileData);
};
main();
}, []);
r,我的 useState 變量以空數組的形式返回,並且在數據完成填充之前首先顯示 console.logs 我做錯了什么
coll.map
map function 對承諾或異步函數一無所知。 它將同步循環遍歷數組,使用 function 的返回值創建一個新數組,然后繼續。
由於 coll.map 將創建一個承諾數組,您應該使用該數組:
const profileData = [];
try {
const promises = coll.map(async (col) => {
// ...
});
await Promise.all(promises);
} catch (error) {
此外,您可以從 map function 返回值,而不是推送到外部數組,promise 將解析為這些值。 這將使您的結果數組與輸入coll
數組的順序相同,並且它將按預期使用map
。 在您的特定情況下,您需要進行一些過濾,因為您想排除沒有名稱的過濾器。
// No longer creating profileData here
try {
const promises = coll.map(async (col) => {
// ...
const obj = {
collection: col,
tokenArray: tokenIds,
image: images,
name: name,
};
return obj
});
let profileData = await Promise.all(promises);
profileData = profileData.filter(obj => obj.name.length > 0);
setR(profileData);
} catch (error) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.