问题
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().
回答1:
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 of getAttachments()
which doesn't return anything, hence the undefined
.
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:
getAttachments($Message['Details']['ID'], message['payload']['parts'][key], function (filename, mimeType, attachment) {
var data = 'data:'+mimeType+';base64,'+attachment.data.replace(/-/g, '+').replace(/_/g, '/');
// now you have the data, you can set the property
$Message['Content']['Attachment'][$Count]['Data'] = data;
});
You will probably have to move other processing of your $Message
into here too, e.g. sending it.
回答2:
getAttachments()
function didn't return any value, that's why it's undefined
.
Solution:
getAttachments($Message['Details']['ID'], message['payload']['parts'][key],function (filename, mimeType, attachment)
{
$Message['Content']['Attachment'][$Count]['Data'] = 'data:'+mimeType+';base64,'+attachment.data.replace(/-/g, '+').replace(/_/g, '/');
});
来源:https://stackoverflow.com/questions/38394107/callback-returning-undefined