0

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

  • Peform a callback? Also you need to then(async (res) => – BGPHiJACK Jul 21 '22 at 23:49
  • *but now recruit isn't accessible outside the promise* Put the code that depends on it inside the promise - either directly inside, or call a function inside the `.then` with the needed data - or `await` the axios call (with try/catch around it, of course) – CertainPerformance Jul 21 '22 at 23:50
  • Why are you using `then` at all in an `async` function? Just write `const res = await axios.get('http://localhost:3000/details');` – Bergi Jul 22 '22 at 02:58

0 Answers0