After extensive research on promises and module creation, I am still unable to understand why my current setup is not functioning properly.
My goal is to write a script that takes a username and then fetches user data from a 3rd party API using a separate module. While everything works fine when the code is in one script, I seem to be making a mistake when trying to extract and separate the API request into its own module. These components are built using durandal as a framework.
Here is the script:
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);
}
};
});
The separate module:
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;
})
}
}
});
Although the API request seems successful and returns the expected JSON object in the console, when pushing it to the nameInfo array, the result is c()
. Upon inspection with Firebug, the file path for the knockout library is revealed.
When attempting an alternative solution:
apiPullMod.apiCaller('v1.4/summoner/by-name', that.name(), 'na').then(function(response){
that.nameInfo.push(response);
console.log(response);
})
The module fails to load, presumably because it lacks a then
property within itself. However, based on the documentation for durandal and requirejs, such a property should not be necessary.
To simplify my question: How can I structure both the module and the calling script to successfully pass a JSON object between them?
NOTE: My personal API key has been included in this post, but I can reset it anytime. There are no concerns about API traffic at this early stage of app development.