Reputation: 828
How can I get a variable in the parameter within a JavaScript function, and then get a Fetch request to send it to the parameter? This is my current code:
//The Function
function spotifyGet(method, variable) {
var authorisationRequest = 'Bearer ' + spotifyAccessToken.access_token;
console.log('Authorisation Request:' + authorisationRequest);
var apiRequest = "https://api.spotify.com/v1/" + method
fetch(apiRequest, {
method: "GET",
headers: {
"Authorization": authorisationRequest
},
})
.then(response => response.json())
.then(response => variable = response) //The variable here isn't the parameter
}
//Calling the function
var sampleVar = {}
spotifyGet('me', sampleVar)
Upvotes: 0
Views: 29
Reputation: 138234
You can't pass "references to variables". You can however pass a function that will get called with the new value, then that function has access to the variable and can change it:
function spotifyGet(method, callback) {
/*...*/.then(response => callback(response));
}
var sampleVar = {}
spotifyGet('me', r => sampleVar = r);
Note: As that callback is asynchronous, further accesses of sampleVar
might or might not return the actual results based on when you access it and wether spotifyGet
was done. In most cases that is not wanted, and sampleVar
should be a promise instead that resolves to the wanted value.
Upvotes: 1