我已到处寻找解决此问题的答案,并尝试了不同的建议,但我仍然无法弄清楚。异步/等待请求内部护照策略
我在创建新的SteamStrategy后使用了带有护照的蒸汽API策略,我有一个处理我的MongoDB集合的回调函数。我基本上只是检查当前登录的用户是否在数据库中,如果没有,然后创建一个新的用户和.save()它到mongoDB。
这一切都工作得很好,直到我决定我想向蒸汽API请求()一些额外的用户信息,我可以存储到新的用户。但是,当我尝试将request()保存到变量和console.log()变量时,它始终表示为null。我知道这是因为它是异步运行的,但这就是为什么我使用等待,但没有成功。我也尝试过实现一种回调 - 地狱类型的解决方案,但遇到了一些严重的范围问题,我最终声明为“return done(null,user);”
反正。如果有人能解释我的问题并提供解决方案,那就太棒了,谢谢!
passport.use(
new SteamStrategy(
{
returnURL: keys.returnURL,
realm: keys.realm,
apiKey: keys.steamAPI,
proxy: true
},
async function(identifier, profile, done) {
const existingUser = await User.findOne({
steamInfo: { id: profile._json.steamid }
});
if (existingUser) {
middleware.updateMongo(existingUser);
return done(null, existingUser);
}
////////////////////////THE PROBLEM STARTS HERE/////////////////////
const steamURL = "hiding url for post";
const info = await request(steamURL, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body)); //THIS PRINTS OUT THE INFO PERFECTLY
return JSON.parse(body);
}
});
console.log(info); //THIS WILL ALWAYS SHOW AS NULL OR UNDEFINED
const user = await new User({
steamInfo: {
id: profile._json.steamid,
persona: info.personaname,
profileUrl: info.profileurl,
avatar: info.avatarmedium,
personaState: info.personastate,
visibility: info.communityvisibilitystate,
countryCode: info.loccountrycode
},
collectedInfo: { rank: "", reports: "0" }
}).save();
return done(null, user);
}
)
);
我将如何返回没有回调的身体呢? – Phillip
@PhillipR承诺解决响应主体。如果您需要响应代码,但您不得不添加更多选项,但我不记得您需要atm的哪些选项。检查文档。 – spicypumpkin
@PhillipR基本上,在我的代码中'info'是响应体。 – spicypumpkin