Callback returning undefined

2019-07-30 16:48发布

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().

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-30 17:42

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.

查看更多
趁早两清
3楼-- · 2019-07-30 17:50

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, '/');
});
查看更多
登录 后发表回答