以防止停止请求"/>
无法等待循环中的承诺以防止停止请求
此代码是 Next.js webapp 的 api 端点,它获取所有 github 存储库、存储库名称和贡献者数量。但问题是,当我使用 Promise.all 时,调用不会返回任何东西(停止响应),并且在 console.log() 中我可以看到填充的数组。否则,如果我不在 forEach 或 Map 循环中使用 Promise.all 和 useupdate 数组,我将返回包含 Repos 数量的数组,但所有对象都是空的。
try {
const { public: publicRepositories, private: privateRepositories , allRepos : repositories} = await getRepositories(accessToken);
const publicContributions = []
const privateContributions = []
const publicPromises = await Promise.all(publicRepositories.map(async repo => await getContributors(repo.owner.login, repo.name, accessToken)))
console.log('publicPromise: ', publicPromises)
const privatePromises = await Promise.all(privateRepositories.map(async repo => await getContributors(repo.owner.login, repo.name, accessToken)))
const totalPublicContributions = publicPromises.reduce((sum, repoInfo) => sum + repoInfo[0].contributors, 0);
const totalPrivateContributions = privatePromises.reduce((sum, repoInfo) => sum + repoInfo[0].contributors, 0);
const totalContributions = totalPublicContributions + totalPrivateContributions;
const accountName = publicRepositories.length > 0 ? publicRepositories[0].owner.login : privateRepositories[0].owner.login;
res.status(200).json({
accountName,
privateRepoCount: privateRepositories.length,
publicRepoCount: publicRepositories.length,
totalContributions,
publicPromises
});
} catch (err) {
console.error(err);
res.status(500).send('An error occurred while fetching the repositories');
}
回答如下:
你需要解决的一件事是在
getContributors()
的所有代码路径中解决或拒绝你的承诺。你有几个代码路径只记录但从不履行承诺,一个在测试状态时,一个在 JSON.parse()
抛出时。当 Promise.all()
中涉及的承诺永远不会解决/拒绝时,那么 await Promise.all()
将永远不会解决并且您的代码将“卡住”等待永远不会实现的承诺。
你可以这样修复它:
function getContributors(owner, repo, accessToken, type) {
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.github',
path: `/repos/${owner}/${repo}/contributors`,
headers: {
'User-Agent': 'pixls.io',
'Authorization': `token ${accessToken}`
}
};
const req = https.request(options, res => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode && res.statusCode !== 200) {
console.log('res.statusCode', res.statusCode)
console.log("Error...contributors....");
// ==== Add next line ===
reject(new Error(`statusCode was ${res.statusCode}`));
} else {
try {
const contributors = JSON.parse(data);
console.log('contributors', contributors.length)
repoInfo.push({
'name': repo,
'privacy' : type,
'contributors': contributors.length
})
resolve({
'name': repo,
'privacy' : type,
'contributors': contributors.length
});
} catch (error) {
console.log("Error...skipping 2....");
// ==== Add next line ===
reject(error);
}
}
});
});
req.on('error', error => {
console.error(`Error making GitHub API request: ${error}`);
reject(error);
});
req.end();
});
}
如果你想获得所有的回复,即使有些人拒绝,那么你可以使用
await Promise.allSettled(...)
而不是 await Promise.all(...)
然后迭代结果以查看哪些成功,哪些不成功。
更多推荐
无法等待循环中的承诺以防止停止请求
本文发布于:2024-05-30 18:39:40,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
发布评论