如何在Gmail阅读消息API中使用异步和等待

时间:2018-11-21 17:52:42

标签: async-await gmail-api google-apis-explorer

我尝试使用async / await代替回调来读取Gmail

这是代码段

const {google} = require('googleapis');
async function getRecentMessageBody(auth) {
    const gmail = google.gmail({version: 'v1', auth});
    try{
       const messageId = await gmail.users.messages.list({
           userId: 'me',
           labelIds: 'INBOX',
           maxResults: 1
        });
      const message = await gmail.users.messages.get({
           userId: 'me',
           id: messageId.data.messages[0].id,
           format : 'full'
      });
      const value = base64url.decode(message.data.payload.body.data);
      console.log(messageId);
     //return value ;
   }
   catch(error) {
     console.log('Error occurs while reading mail :'+ error);
     throw error;
   }
}

但是messageId未定义

如果我使用

gmail.users.labels.list({
    userId: 'me',
}, (err, res) => {
   if (err) return console.log('The API returned an error: ' + err);
   const labels = res.data.labels;
   if (labels.length) {
      console.log('Labels:');
      labels.forEach((label) => {
        console.log(`- ${label.name}`);
      });
   } else {
      console.log('No labels found.');
   }
});

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

使用promisfy将回调转换为promises