Struggling with understanding Promises and implementing them on the backend. Even after reading multiple stackoverflow posts, it seems like I'm not alone.
I specifically need assistance on passing the result of a resolved promise within my code. In the snippet below, I am fetching data from the starwars API using axios.get, which returns a promise. I then resolve it using .then and want to write it onto a MongoDB atlas collection.
The frontend scenario, such as React's setState method, works fine when changing state within the .then function. However, I'm encountering difficulties making it work in the backend environment.
If you could guide me on the necessary changes needed to successfully write to MongoDB Atlas, that would be greatly appreciated.
var axios = require("axios");
const MongoClient = require("mongodb").MongoClient;
var db;
const getData = () => {
return axios
.get("https://swapi.co/api/people/1")
.then(response => {
if (!response.data) throw Error("No data found.");
console.log(JSON.stringify(response.data)) **//This returns the data as expected.**
return JSON.stringify(response.data);
})
.catch(error => {
console.log(error);
throw error;
});
};
console.log(getData()); **// This returns {Promise <pending>}**
const client = new MongoClient(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
});
// Connect to database and insert default users into users collection
client.connect(err => {
console.log("Connected successfully to database");
let d = {
name: "Luke Skywalker",
height: "172",
mass: "77",
hair_color: "blond",
skin_color: "fair",
eye_color: "blue"
};
db = client.db(process.env.DB_NAME);
db.collection("macroData").insertOne(d); //this works
db.collection("macroData").insertOne(getData); // this doesn't work as it still appears to be a promise
});