Return value from inside fetch

Asked

Viewed 297 times

0

I’m trying to read a local Javascript file and put your data into a variable and so far I’ve written the following code:

function fetchDictionary() {
    const URL_TO_FETCH = './lang-portuguese.txt';
    fetch(URL_TO_FETCH).then(res => res.text())
    .then(data => obj = data).then((data) => {
        console.log(data)
    })
}

function buildWords() {   
    console.log(fetchDictionary())
}

And it works properly, on the console appears the contents of the file if I call the fetchDictionary().

But if I change the console.log(data) by a return data; and I try to call that function fetchDictionary() in function buildWords(), she only returns one undefined.

What mistake am I making? I’ve read several documentations, tutorials and I can’t see where I went wrong.

1 answer

3


It turns out that the fetch returns a promise and, therefore, you can use the value using the then or await and not directly:

function fetchDictionary() {
    const URL_TO_FETCH = './lang-portuguese.txt';
    return fetch(URL_TO_FETCH).then(res => res.text())
    .then(data => obj = data).then((data) => {
        console.log(data);
        return data;
    })
}

function buildWords() {   
    fetchDictionary()then(console.log);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.