0

I want to fetch some data from a public API and then modify this data. For example, I will add a Point(long, lat) in geography in Postgis. However, I need to fetch the data from a public API before I get there. I have tried this so far, but it doesn't seem like the logic makes sense.

Inserting data into the database works fine, and I have set it up correctly. However, the problems happen when I try to do it in a JSON function.

require('dotenv').config()
const express = require('express')
const fetch = require('node-fetch');
const app = express();
const db = require("./db");
app.use(express.json());

async function fetchDummyJSON(){
    fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(res => res.json())
    .then((json) => {
        await db.query("INSERT INTO logictest(userId,id,title,completed) values($1,$2,$3,$4)",[json.userId+1,json.id,json.title,json.completed])
    });
}
fetchDummyJSON()


  app.get('/', (req, res) => {
    res.send('Hello World!')
  });

const port = process.env.PORT || 3001
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
  })

I keep getting SyntaxError: await is only valid in async functions and the top-level bodies of modules; however, fetchDummyData() is an async function from what I can tell. Is there a way to make more sense or make this work? I am going for a PERN stack.

1 Answer 1

1

This is a function as well:

.then((json) => {
            await db.query("INSERT INTO logictest(userId,id,title,completed) values($1,$2,$3,$4)",[json.userId+1,json.id,json.title,json.completed])
        });

try

.then(async (json) => {
        await db.query("INSERT INTO logictest(userId,id,title,completed) values($1,$2,$3,$4)",[json.userId+1,json.id,json.title,json.completed])
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it worked, but do you know of a smarter way to do this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.