I’m staying close to the Hiker Tutorial with a backend.js and context.js and I get a “Uncaught TypeError: Cannot read property ‘then’ of undefined” in my context.js
I’m fetching a JSON formatted response in the backend.js, which I then want to work with in context.js.
backend.js:
var friendsGetUrl = 'https://api.vk.com/method/friends.get?user_id=';
function getFriends(userid){
fetch(friendsGetUrl + userid.value)
.then(function(result) {
return result.json();
})
.then(function(resultJson) {
console.log("result=" + JSON.stringify(resultJson));
return JSON.stringify(resultJson);
})
.catch(function(err) {
console.log("err_backend" + err);
});
}
module.exports = {
getFriends: getFriends
};
context.js:
var Observable = require("FuseJS/Observable");
var Backend = require("./Backend");
var friends = Observable();
function getFriends(userid){
Backend.getFriends(userid)
.then(function(newFriends){
friends.replaceAll(newFriends);
})
.catch (function(error) {
console.log("Couldn't get friends: " + error);
});
}
module.exports = {
friends: friends,
getFriends: getFriends
};
The reason I think that the code in the context.js is ‘outrunning’ the code is the backend is that I get the error message before the result from the backed is logged.
I understand the basic concept of promise, just difficult to get my head around it in practice
Ultimately I want to create an observable with friends of friends.
Thanks!