我正在使用 response
Node 库发出一个 http 请求,并且我尝试递归地调用它(如果用户在某一天进行了提交,请检查前一天。如果没有,请计算所有天数以获得连续记录)。
问题在于该行
const githubResponse = await request(options);
吐出错误
Unexpected token o in JSON at position 1
await request(options)
似乎没有返回我期望的 JSON GitHub API 响应,但 githubResponse
似乎是一个我无法使用的对象。我猜我使用 async/await
的方式不正确,但我不知道如何修复它。
async function checkUserCommitForDate(user, date) {
const options = {
url: `https://api.github.com/search/commits?q=author:${user}+author-date:${date}`,
headers: {
'User-Agent': 'request',
'Accept': 'application/vnd.github.cloak-preview'
}
};
const githubResponse = await request(options)
// I get an error on the next line
if (JSON.parse(githubResponse).total_count > 0) {
const previousDaysDate = moment(date).subtract(1, 'day').format('YYYY-MM-DD');
let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
streakCounter++;
console.log('streakCounter', streakCounter);
return streakCounter;
} else {
return 0;
}
}
更新:这似乎不是一个 promise ,所以我需要以不同的方式格式化它(作为回调)。当我尝试这个时:
async function checkUserCommitForDate(user, date) {
const options = {
url: `https://api.github.com/search/commits?q=author:${user}+author-date:${date}`,
headers: {
'User-Agent': 'request',
'Accept': 'application/vnd.github.cloak-preview'
}
};
request(options, async function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
if (JSON.parse(body).total_count > 0) {
const previousDaysDate = moment(date).subtract(1, 'day').format('YYYY-MM-DD');
let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
streakCounter++;
console.log('streakCounter', streakCounter);
return streakCounter;
} else {
return 0;
}
});
}
线路
let streakCounter = await checkUserCommitForDate(user, previousDaysDate);
成为问题,因为streakCounter
未定义,使得日志NaN
。
最佳答案
正如评论中所述request使用回调而不是返回 promise ,并且您实际上不需要自己 promise 它,因为已经有一个名为 request-promise 的包。 .
在代码中使用它应该可以直接与async/await
一起使用
关于node.js - 通过 Node 请求包递归使用 async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857653/