回调返回未定义 [英] Callback returning undefined

查看:269
本文介绍了回调返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从GMail API中获取数据,以便能够从那里加载base64加密中的附件数据,尽管当我尝试返回它时,我却不确定.

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

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

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

推荐答案

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

It is not the callback returning undefined - it is getAttachments().

对GMail API的调用是异步的,因此您不能以这种方式分配给$Message...['Data']-您实际上是在分配getAttachments()的结果,该结果不返回任何内容,因此不会返回undefined.

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

您可能还必须将对$Message的其他处理也移到此处,例如发送.

You will probably have to move other processing of your $Message into here too, e.g. sending it.

这篇关于回调返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆