Not returning the fetch properly or "Uncaught TypeError: Cannot read property 'then' of undefined"

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 :wink:

Ultimately I want to create an observable with friends of friends.

Thanks!

Hi!

Your problem here is that your function in backend.js function getFriends(userid) is not returning anything.

Simple fix is to just add return behind your fetch:

function getFriends(userid){
	return fetch(friendsGetUrl + userid.value)
		.then(function(result) {
			return result.json();
		}).catch(function(err) {
			console.log("err_backend" + err);
		});
}

you’re also returning a serialized version of your JSON (by doing JSON.stringify(…)). I’m not sure why you would be doing this, so i removed it.

Since your backend.js function is fetching, i would call this function fetchFriends instead. Then you can more easily differentiate the two functions (the one in context.js and the one in backend.js).