V
V
Vladimir2019-11-11 21:28:27
JavaScript
Vladimir, 2019-11-11 21:28:27

Why is the promise response empty?

Good evening. Please tell me. I'm trying to get information from the server using a promise, but the answers are empty.
Customer:

const sendMenu = ms => {
        return new Promise(r => setTimeout(() => r(), ms))
      }

      const url = 'http://localhost:3000/menu'

      function fetchTodos() {
        console.log('Fetch todo started...')
        return sendMenu(2000).then(() => {
          return fetch(url)
        })
        .then(response => response)
      }

      fetchTodos()
        .then(data => {
          console.log('Data: ',data)
        })
        .catch(e => console.error(e))

Server:
app.post('/menu', (req,res) => {

    let viewmenu;

    connection.query('SELECT * FROM menu', (err, result) => {
        if(err) {
          console.error(err);
          return;
        }

        const index = result.reduce((acc, row) => ({...acc, [row.id]: row}), {});
          var menu = [];
          for(const row of result) {
              if(row.parent_id === 0) {
                menu.push(row);
                continue;
              }
              const parent = index[row.parent_id];
              if(!parent) {
                console.warn(`Undefined parent with id ${row.parent_id}`);
                continue;
              }
              if(!parent.children) {
                parent.children = [];
              }
              parent.children.push(row);
              
        }

        viewmenu = menu;

    });

    const sendMenu = ms => {
      return new Promise(r => setTimeout(() => r(), ms))
    }

    sendMenu(200).then(() => res.send(viewmenu))

})

5dc9a8db1a420266971493.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2019-11-12
@abberati

Because the answer, the server, goes first, and then the data is received from the database. Move the response code inside the callback for getting data from the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question