So I'm fetching data from an api using axios. I'm then using that data to build an object that I want to eventually save to my mongodb collection.
I kept debugging and trying a console.log everything and reached an understanding of sorts.
app.get('/', async (req, res) => {
let initialData = {};
axios.get('http://localhost:3000/details').then((res) => {
initialData = res.data;
});
const recruit = new RecruitModel({ email:initialData.email,
mobile_number:initialData.mobile_number,
name:initialData.name});
try {
await recruit.save()
res.send("inserted data")
} catch (error) {
console.log(error)
}
})
The issue is that I have to affect the values to recruit
inside the promise because the data isn't accessible outside. If I put
app.get('/', async (req, res) => {
let initialData = {};
axios.get('http://localhost:3000/details').then((res) => {
initialData = res.data;
const recruit = new RecruitModel({ email:initialData.email,
mobile_number:initialData.mobile_number,
name:initialData.name});
});
try {
await recruit.save()
res.send("inserted data")
} catch (error) {
console.log(error)
}
})
If I change it to this and console.log(recruit)
the values actually are affected. but now recruit isn't accessible outside the promise.
If I add that try catch block like so,
app.get('/', async (req, res) => {
let initialData = {};
axios.get('http://localhost:3000/details').then((res) => {
initialData = res.data;
console.log(initialData);
const recruit = new RecruitModel({ email:initialData.email,
mobile_number:initialData.mobile_number,
name:initialData.name});
console.log(recruit);
try {
await recruit.save()
res.send("inserted data")
} catch (error) {
console.log(error)
}
});
})
I get this error
SyntaxError: await is only valid in async functions and the top levelbodies of modules