RequireJS模块从API服务器接收JSON,返回undefined

RequireJS module receives JSON from API server, returns undefined?

本文关键字:JSON 返回 undefined 模块 API 服务器 RequireJS      更新时间:2023-09-26

我已经做了各种关于承诺和模块创建的阅读,我不明白为什么这不会工作。

我正在写一个脚本,需要一个用户名,然后使用一个单独的模块从第三方API获取用户数据。我可以得到一切工作良好,当它放入相同的脚本,但我做了一些错误,当我拉出来,并将API请求分离到自己的模块。这些都是用durandal作为框架构建的。

脚本:

define(function(require) {
var http = require('plugins/http'),
    ko = require('knockout'),
    apiPullMod = require('apiPullMod');
return {
    name: ko.observable('RyeBrush'),
    nameInfo: ko.observableArray([]),
    getSummoner: function() {
        var that = this;
        if (!that.nameInfo()) {
            return;
        } else {
            that.nameInfo.push(apiPullMod.apiCaller('v1.4/summoner/by-name', that.name(), 'na'))
        };
        console.log(that.nameInfo);
    }
};
});

模块:

define(['plugins/http'], function(http) {
return {
    apiCaller: function(apiType, apiUserId, region) {
        http.get('https://' + region + '.api.pvp.net/api/lol/' + region + '/' + apiType + '/' + apiUserId + '?api_key=282d6dcb-a047-4262-88d0-c53b0e28e6ef', 'jsoncallback').then(function(response) {
            console.log(response);
            return response;
        })
    }
}
});

我可以从控制台看到API请求是成功的,我得到了预期的JSON对象,一切似乎都很好。然而,当我把它推到nameInfo数组时,我得到的是:c(),在firebug中悬停在这个上面,给了我knockout库的文件路径。

当我尝试这个:

 apiPullMod.apiCaller('v1.4/summoner/by-name', that.name(), 'na').then(function(response){
                that.nameInfo.push(response);
                console.log(response);
            })

模块不会加载,我想是因为我没有将then属性写入模块本身。然而,当我阅读关于此上下文中的延迟和需求的文档时,它读到我不应该需要?

如果我必须把它归结起来,我的问题是:我如何格式化我的模块,以及调用它的脚本,将JSON对象从一个传递到另一个?

注意:我在这个问题中包含了我的个人API密钥,因为我可以根据需要重置它。在应用开发的早期阶段,我并不担心API流量。

如果你改变apiCaller返回一个承诺,它可能会工作,像这样

define(['plugins/http'], function(http) {
    return {
        apiCaller: function(apiType, apiUserId, region) {
            return http.get('https://' + region + '.api.pvp.net/api/lol/' + region + '/' + apiType + '/' + apiUserId + '?api_key=282d6dcb-a047-4262-88d0-c53b0e28e6ef', 'jsoncallback');
        }
    };
});
apiPullMod.apiCaller('v1.4/summoner/by-name', that.name(), 'na').then(function(response){
    that.nameInfo.push(response);
    console.log(response);
});

看起来http插件正在使用knockout的map插件来自动将您的响应转换为可观察对象。我建议使用jquery的http插件或其他。