如何在发送新消息之前让电报bot等待?

问题描述

所以,我有这段代码,将从Google日历中提取接下来7天的所有事件,并通过电报机器人将其发送回去。

function GetEvents(chatId) {    
    const StartDate = new Date();
    console.log(StartDate);
    const EndDate = new Date();
    EndDate.setDate(EndDate.getDay() + 12);
    console.log(EndDate);
    calendar.calendarList.list({})
        .then(res => {
            const calendarId = res.data.items[0].id;
            calendar.events.list({
                calendarId: calendarId,orderBy: 'startTime',singleEvents: true,timeMax: EndDate,timeMin: StartDate
            })
            .then(events => {
                events.data.items.forEach(item => {
                    bot.sendMessage({
                        chat_id: chatId,text: `Materia: ${item.summary}\nCompiti: ${item.description}`
                    });
                });
            })
            .catch(err => console.error('Get Event List error: ' + err));
        })
        .chat(err => console.error('Get Calendars List error: ' + err));
}

,但机器人的消息未按顺序到达我(Google Api响应的顺序正确)。我知道我必须放await,但找不到位置。我尝试过:

async function GetEvents(chatId) {    
    const StartDate = new Date();
    console.log(StartDate);
    const EndDate = new Date();
    EndDate.setDate(EndDate.getDay() + 12);
    console.log(EndDate);
    calendar.calendarList.list({})
        .then(res => {
            const calendarId = res.data.items[0].id;
            calendar.events.list({
                calendarId: calendarId,timeMin: StartDate
            })
            .then(events => {
                events.data.items.forEach(item => {
                    await bot.sendMessage({
                        chat_id: chatId,text: `Materia: ${item.summary}\nCompiti: ${item.description}`
                    });
                });
            })
            .catch(err => console.error('Get Event List error: ' + err));
        })
        .chat(err => console.error('Get Calendars List error: ' + err));
}

控制台说await can be use only in async functions,但是如果您看我在该函数中放置了async。 谁能帮我吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)