从Google API向Discord.js发送数据时,如何避免待处理的承诺? [英] How to avoid pending promises when sending data from google api to discord.js?
问题描述
我正在研究Discord机器人,该机器人可以从Excel工作表中提取数据.例如,当我问机器人:!adress paul"时,我希望机器人在工作表的列A中寻找"paul"值,然后返回列B(值Paul所在行的值)是)在不和谐应用中.
I am working on a Discord bot which could extract datas from an Excel sheet. For example when I will ask the bot : "!adress paul", I would like the bot to look for "paul" value in the column A of a sheet and return the value of the column B (of the row where the value Paul is) in the discord app.
到目前为止,我已经成功地从Excel工作表中读取数据并在console.log中报告了数据(当我在函数内部调用console.log时).但是,每次我从函数中调用值时,都会出现一个"Promise {}"……我在网络上进行了许多研究,但都没有找到解决方案.
So far, I succeeded to read data from the Excel sheet and report the datas in the console.log (when I call the console.log inside the function). However each time I call the value out of the function I have a 'Promise {}' that appears... I made many many research on the web, without finding the solution.
const discord = require('discord.js');
const {google} = require('googleapis');
const keys = require('./identifiants.json');
// Creation of the Spreadsheet client
const client1 = new google.auth.JWT(keys.client_email, null,
keys.private_key, ['https://www.googleapis.com/auth/spreadsheets']);
client1.authorize(function(err, tokens)
{
if(err)
{
console.log(err);
return;
}
else
{
console.log('Connected to Google Sheets');
}
});
// Creation of the Discrod client
const client2 = new discord.Client();
client2.on('ready', () =>
{
console.log('Connected to Discord');
});
// Create an event listener for messages
client2.on('message', message =>
{
if (message.content === '!address')
{
console.log("OK 1");
let paul = address(client1);
console.log(paul);
console.log("OK2");
}
});
async function address(client)
{
const gsapi = google.sheets({version:'v4',auth: client });
const opt1 = {spreadsheetId: 'ID OF MY SPREADSHEET', range: 'Sheet1!A1:B3'};
let data = await gsapi.spreadsheets.values.get(opt1);
return data.data.values;
}
client2.login("MY CLIENT LOGIN")
在控制台中,"OK1"和"OK2"之间出现消息"Promise {pending}".有人可以帮我吗?我将非常感谢
In the console the message "Promise {pending}" appears between "OK1" and "OK2". Can someone help me on that case please? I would be very grateful
推荐答案
您的 address
函数是 async 函数,因此它将返回承诺.
Your address
function is an async function so it will return a promise.
因此,您将需要使用 then
来获取值:
Therefore, you will need to use then
to get the value:
client2.on('message', message => {
if (message.content === '!address') {
address(client1)
.then(paul => {
console.log(paul);
});
}
});
或者,您可以使用 async-await :
client2.on('message', async (message) => {
if (message.content === '!address') {
let paul = await address(client1);
console.log(paul);
}
});
这篇关于从Google API向Discord.js发送数据时,如何避免待处理的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!