U
U
uzi_no_uzi2021-05-12 22:45:17
Node.js
uzi_no_uzi, 2021-05-12 22:45:17

How to fetch data using fetch?

There is such an endpoint on the back

app.get('/api/category', async(req, res) => {
    try {
        let categories = await Category.find({});
        res.send(categories)
    } catch(e) {
        res.send(e)
    }
});


Next, I try to fetch data on the front using fetch:

async function getCategories() {
        let categories;

         await fetch(`${api}/category`)
        .then((res) => {
            return res.json();
        }).then((response) => {
            categories = response;
        })
        .catch((e) => {
            console.log(e);
        })

        return categories;

    }


But in the console I get Promise Pending
609c3005844cc168710048.png

What am I doing wrong? The most interesting thing is that if we do console.log(response) in the second .then, we will get the expected result. I can't figure out how to just return data from a function.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kxnkxv, 2021-05-12
@kxnkxv

const categories = await getCategories();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question