Callback returning undefined

旧街凉风 提交于 2019-12-24 08:23:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!