0

My goal is to get data from MongoDB atlas in the react app. Even after writing .then and .catch with axios.get() I'm getting an unresolved promise.

My code:

const entry = axios.get('http://localhost:3001/user')
                .then(res=>{
                    console.log(res.data)
                    return res.data;
                })
                .catch(err=>{console.log("Error: "+err)})
console.log(entry);

The above snippet has the following output

Promise {<pending>}
(5) [{…}, {…}, {…}, {…}, {…}]

Here console.log(res.data) is giving me the array whereas console.log(entry) is giving me a pending promise.

Here is the nodejs code when I retrieve data from MongoDB atlas

const express = require('express');
const Route = express.Router();
const Note = require('../models/note');

Route.get('/', async(req, res)=>{
    await Note.find()
    .then(notes=>res.send(notes))
    .catch(err=>res.send("Error: "+err))
})
module.exports = Route;
Striker
  • 67
  • 7
  • Clearly `entry` is a Promise - which is the only return from `axios.get`. No mater how much you want to try to turn a promise into that data array, the function is designed to return a promise - and that is the behavior you see here. – Randy Casburn Apr 04 '21 at 19:45
  • it is possible you're confusing this behavior with `async`/`await` which makes it appear to magically return the data, but you still have to deal with the promise returned from the `async` function. So no matter how you look at it, you'll be dealing with a promise. – Randy Casburn Apr 04 '21 at 19:48
  • If axios only returns a promise then how can I use the array I received from the ```axios.get```. Moreover when i wrote ```.then(res=>{ console.log(res.data);return res.data;})``` what is the significance of return statement (because I'm trying to return an array but instead a promise is returned) – Striker Apr 04 '21 at 20:08
  • A `return` in `then()` returns to the next `then()` in the chain (if there is one). A return in a callback function almost never returns to the outer function – charlietfl Apr 04 '21 at 20:19
  • A promise is asynchronous. You can't eat a pizza before it gets delivered – charlietfl Apr 04 '21 at 20:20

1 Answers1

1

This is part of the javascript event loop. The event loop gets it's name because it's synchronously waiting for messages to arrive. It's actually monitoring the Callback Queue, So if the call stack is empty, it will take the first event from the call back queue and will push it to the Call Stack, which effectively runs it.

So, let's break down your code and will try to understand what's going on:

const entry = axios.get('http://localhost:3001/user') // 1
            .then(res=>{                              // 2
                console.log(res.data)                 // 3
                return res.data;
            })
            .catch(err=>{console.log("Error: "+err)})
console.log(entry);                                   // 4
  1. // 1 is being added to the call stack and executed.
  2. // 2 is being excuted by the web api (threads that JS make calls to them. They are the pieces of the browser in which the concurrency does it's magic)
  3. The browser set up to listen for the response from the network, when it will have something to return. it will schedule the callback function to be executed by inserting it into the call back queue (and the event loop will fetch in it's next visit in the call back queue).
  4. // 4 Is being added to the call stack and executed. hence, entry is not in rejected/ resolved state.
  5. After a while. the network returns with response and pushes the callback to the Callback Queue.
  6. The Event Loop takes that callback from the Callback Queue and pushes it to the Call Stack.
  7. That call back is executed and adds console.log(res.data) to the Call Stack.
  8. console.log(res.data) is executed.

You can read more about it here:

https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5

Ran Turner
  • 14,906
  • 5
  • 47
  • 53