回调返回undefined

时间:2016-07-15 10:42:10

标签: javascript jquery asynchronous callback gmail-api

我试图从GMail API获取数据,以便能够从base64加密加载附件数据,但是当我尝试返回它时,我得到了未定义。

$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);
     });
}

问题似乎是在函数返回值后数据可用。这已经通过console.log()进行了测试。

2 个答案:

答案 0 :(得分:1)

返回未定义的回调不是 - getAttachments()

对GMail API的调用是异步的,因此您无法以这种方式分配给$Message...['Data'] - 您实际上是在分配getAttachments()的结果,而这些结果并不会返回任何内容,因此{ {1}}。

在您进行实际回调之前,您无法获得数据,因此您需要在回调本身中设置值:

undefined

您可能还必须将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; }); 的其他处理内容移至此处,例如发送它。

答案 1 :(得分:0)

getAttachments()函数没有返回任何值,这就是undefined的原因。

解决方案:

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, '/');
});