代码之家  ›  专栏  ›  技术社区  ›  questionar

如何在gmail read message api中使用async和await

  •  1
  • questionar  · 技术社区  · 7 年前

    我尝试使用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 回复  |  直到 6 年前
        1
  •  1
  •   questionar    6 年前

    使用promisfy将回调转换为承诺