GMail API pagination use of nextPageToken

前端 未结 1 1178
栀梦
栀梦 2021-01-14 13:57

Have spent hours searching Google et. al. for an answer, sure it\'s simple but how do you create pagination with the GMail api using nextPageToken? what ever I do cannot ge

相关标签:
1条回答
  • 2021-01-14 14:46

    You could save the next page token on every request and use it in your next request. If there is no next page token in the response, you know that you have gotten all messages:

    function listMessages(pageToken) {
      return new Promise(function(resolve) {
        var options = {
          userId: 'me',
          maxResults: 10
        };
        if (pageToken) {
          options.pageToken = pageToken;
        }
        var request = gapi.client.gmail.users.messages.list(options);
        request.execute(resolve);
      });
    }
    
    function getMessage(message) {
      return new Promise(function(resolve) {
        var messageRequest = gapi.client.gmail.users.messages.get({
          userId: 'me',
          id: message.id
        });
        messageRequest.execute(resolve);
      });
    }
    
    var pageToken;
    function displayInbox(){
      listMessages(pageToken).then(function (response) {
        if (response.nextPageToken) {
          pageToken = response.nextPageToken; // Get the next page next time
        } else {
          console.log('No more pages left!');
        }
        if (response.messages) {
          Promise.all(response.messages.map(getMessage)).then(function (messages) {
            messages.forEach(appendMessageRow);
          });
        }
      })
    }
    
    0 讨论(0)
提交回复
热议问题