javascript - 将请求答案存储在变量中
问题描述
JavaSript 的新手我目前正在使用 API 开发一个不和谐的机器人。而且我想知道如何将请求答案存储在一些变量中,以便以后可以使用它们来写入 .json 文件。
使用的API:https : //wiki.guildwars2.com/wiki/API:2/account(我可以用console.log毫无问题地显示答案,但我无法存储它们:/)
bot.on('message', message => {
if (message.content.startsWith(config.prefix+"add")){
const fs = require('fs') //importing file save
var fPath = './data.json'
var fRead = fs.readFileSync(fPath);
var fFile = JSON.parse(fRead); //ready for use
var userId = message.author.id //user id here
var n; var g;
if (!fFile[userId]) { //this checks if data for the user has already been created
cut=message.content.replace("?add ", "");
api.authenticate(cut).account().blob().then(request=> n=(request.account.name))
api.authenticate(cut).account().blob().then(request=> g=(request.account.guilds));
fFile[userId] = {key: cut, uidgw2:n, guild: g, role:""} //if not, create it
fs.writeFileSync(fPath, JSON.stringify(fFile, null, 2));
} else {
message.reply("Déjà dans la base.");
console.log(message.author.id+" déjà dans data.json");
}
}
})
我的问题是 n & g 显然是未定义的,所以我在我的 .json 文件中得到了它:
{
"231452514608360960": {
"key": "B1257308-125X-8040-A55B-0AD1CF03480DF08F4AC2-9326-44DC-83A6-75A950C5ADFA",
"role": ""
}
}
即使我在 bot.on 或内部声明它们,仍然未定义,而且我对 js 和 api 请求了解不多......
解决方案
编辑:基于添加到原始问题的进一步解释:
您必须记住,来自 API 调用的承诺在初始传递后得到解决。但是您尝试使用第一遍中已经存在的值。
像这样的东西应该工作:
Promise.all([api.authenticate(cut).account().blob(),
api.authenticate(cut).account().blob()])
.then((requests) => {
n = requests[0].account.name;
g = requests[1].account.guilds;
fFile[userId] = {key: cut, uidgw2:n, guild: g, role:""} //if not, create it
fs.writeFileSync(fPath, JSON.stringify(fFile, null, 2));
});
});
您还没有显示这里失败的原因,但如果我猜我会说您的问题与您在消息回调外部和内部声明“n”和“g”的事实有关。
你有
var n; var g;
在回调内部,但也在前两行。
如果您删除回调内部的声明,您将能够访问外部的值。
推荐阅读
- data-modeling - 使用 DWH / Dimensional Model 中的主键来搜索功能
- admin - Hyperledger Fabric Composer 应用程序中对等管理员的访问控制
- kernel - 在 OpenCL 中多次执行相同的内核
- python - 根据条件最小值/最低点值过滤数据帧(python/pandas)
- javascript - 使用 gulp 4 进行的 gulp 监视任务
- android - 是否可以从我的应用程序写入内部存储?
- javascript - 默认情况下,Angularjs复选框在加载时选中,在具有ng-true-value的表单中不起作用
- html - 导航栏未居中
- python - 使用浏览器打开网页后如何访问html
- git - 在 git 中推送与在 github 中上传