这是我的代码:
app.get("/", (req, res) => {
const reducer = (acc, guildCount) => acc + guildCount;
const results = client.shard.fetchClientValues('guilds.cache.size');
console.log(results)
let guildCount = results.reduce(reducer, 0)
console.log(guildCount)
renderTemplate(res, req, "index.ejs", { guildCount });
});
一些详细信息:`
client.shard.FetchClientValues('guilds.cache.size')
返回承诺{
。
当我要加载以下错误时:typeerror:results.reduce不是一个函数
``
这段代码的工作原理是:
client.shard.fetchClientValues('guilds.cache.size')
.then(results => {
console.log(`${results.reduce((acc, guildCount) => acc + guildCount, 0)} total guilds`);
})
.catch(console.error);
但是我必须在变量中定义结果,以便导出它。
我该怎么解决这个问题?有没有另一种方法用reduce定义结果?
你的第二种方法是正确的。您的方法必须是异步的,从那一点开始。一旦异步,始终异步。无法强制它回到同步状态。
幸运的是,您所在的.get()
方法已经是异步的,因此只需将之后的所有内容移到.then()
:
app.get("/", (req, res) => {
const reducer = (acc, guildCount) => acc + guildCount;
client.shard.fetchClientValues('guilds.cache.size')
.then(results => {
console.log(results)
let guildCount = results.reduce(reducer, 0)
console.log(guildCount);
renderTemplate(res, req, "index.ejs", { guildCount });
}).catch(console.error);
});
const results = client.shard.fetchClientValues('guilds.cache.size');
是在回报一个承诺。而当你在没有。then()的情况下使用它时
您将得到一个承诺对象作为回报,而不是结果数组。
const results = await client.shard.fetchClientValues('guilds.cache.size');
要修复这个问题,您可以使用异步等待
app.get("/", async (req, res) => {
const reducer = (acc, guildCount) => acc + guildCount;
const results = await client.shard.fetchClientValues('guilds.cache.size');
console.log(results)
let guildCount = results.reduce(reducer, 0)
console.log(guildCount)
renderTemplate(res, req, "index.ejs", { guildCount });
});
reduce
是数组帮助器,其中result
是promise
,
因此,您的操作要么在然后
中进行,就像
client.shard.fetchClientValues('guilds.cache.size').then(results => results.reduce(reducer, 0))
或
使用async
await
const start = async () => {
...
const results = await client.shard.fetchClientValues('guilds.cache.size')
results.reduce(reducer, 0)
...
}
start()