Here I have the code:
function request(data) {
...
var result;
var req = fetch(url).then((resp) => resp.json()).then(function(dat) {
result = dat[0][0][0];
return result;
})
r = request("...")
// Aqui ^ obtengo "undefined"
What I want is to save the value dat[0][0][0]
and then return it, to use it again. Can somebody help me?
What you should do is use the logic of what you want to do inside the function, since since you are using .then the value will only exist inside it. That is why you get undefined when you call the function:
The same thing happened to me and this is how I solved it.
A combination must be made between async and await.
In the function you have
request()
, you should return the fetch promise and add the async keyword to the fetch definition.Here's a page showing usages with examples
EDIT: To make use of await, it must be used inside an async function, so you have two options.