I'm trying to get data from the GMail API to be able to load attachment data from there base64 encryption though when I try to return it I am getting undefined.
$Message['Content']['Attachment'][$Count]['Data'] = getAttachments($Message['Details']['ID'], message['payload']['parts'][key], function (filename, mimeType, attachment) {
return 'data:'+mimeType+';base64,'+attachment.data.replace(/-/g, '+').replace(/_/g, '/');
});
function getAttachments(messageID, parts, callback) {
var attachId = parts.body.attachmentId;
var request = gapi.client.gmail.users.messages.attachments.get({
'id': attachId,
'messageId': messageID,
'userId': 'me'
});
request.execute(function (attachment) {
callback(parts.filename, parts.mimeType, attachment);
});
}
The problem seems to be that the data is being made available after the function has returned a value. This has been tested through console.log().
It is not the callback returning undefined - it is
getAttachments()
.The call to the GMail API is asynchronous, so you cannot assign to
$Message...['Data']
in this way - you are actually assigning the result ofgetAttachments()
which doesn't return anything, hence theundefined
.You won't have the data available until you are in the actual callback, so you need to be setting the value in the callback itself:
You will probably have to move other processing of your
$Message
into here too, e.g. sending it.getAttachments()
function didn't return any value, that's why it'sundefined
.Solution: