I'm having some issues understanding variables and functions using fetch. I'm trying to pass the value of response from
.then(response => response.json())
to
.then(lang => response['lang'].slice(-2)
But I am getting the undefined variable response error, so I'm not referencing the variable correctly. What's the correct way of calling it?
Also I want to call both console logs, the piece of code below currently does that but I don't think I should be overwriting response function, can I call a function without arguments or the commands by themselves?
.then(response => console.log(response['text']) & console.log(food))
console.log(response['text']) & console.log(food)
fetch("https://localhost:8000", {method:"POST", body:fd})
.then(response => response.json())
.then(lang => response['lang'].slice(-2))
.then(food => "Temporary")
.then(function detectType(lang) {
switch(lang) {
case 'abc':
food = "Bananas";
break;
case 'def':
food = "Apples";
break;
default:
food = "Bananas";
break;
}})
.then(response => console.log(response['text']) & console.log(food))
.catch(err => console.error(err));
}
lang
? You are not doing anything with it. It should be.then(response => response['lang'].slice(-2))
(but it doesn't matter what you call the parameter). Parameters are only accessible in the function they are defined in. See also What is the scope of variables in JavaScript?'a'
. Example:var foo = {text: 'a'}; console.log(foo['text']);
.console.log(response['text']) & console.log(food)
. If I do.then(response => response['lang'].slice(-2))
, won't the response that is currently{'text':'a', 'lang':'bbb'}
become only 'b'? @FelixKling.then
s are chained. The next.then
callback receives whatever the previous callback returns. The parameter names having nothing to do with each other (i.e.response
in.then(response => console.log(response['text']) & console.log(food))
has nothing to do with.then(response => response.json())
. Again, parameters are scoped the functions. Here is a simplified example of your problem:function foo(bar) { }; foo(42); console.log(bar);
...