Reputation: 23
The 'getData' function in the 'dataService' class performs a GET request to the API and the console.log in the 'updateData' function does print the right information but an empty object is returned for 'http://localhost:xxxx/api/data'. I think it is due to a problem with asynchronous but I can't figure out how to fix it. Any ideas?
dataService.ts:
import { Format } from '../types';
import axios from 'axios';
const token = process.env.TOKEN;
const url = `https://www.something.com/somequery?someapikey=${token}`;
const getData = async () => {
try {
const response = await axios.get<Format>(url);
return response.data;
} catch (error) {
console.error(error);
}
};
const updateData = async (): Promise<Format | undefined> => {
const allData = await getData();
console.log(allData, 'allData in backend');
//edit allData to suitable format here
return allData;
};
export default {
updateData
};
data.ts:
import express from 'express';
import dataService from '../services/dataService';
const router = express.Router();
router.get('/', (_req, res) => {
res.send(dataService.updateData());
});
export default router;
index.ts:
import express from 'express';
const app = express();
...
import dataRouter from './routes/data';
...
app.use(express.json());
...
app.use('/api/data', dataRouter);
...
Upvotes: 0
Views: 1874
Reputation: 795
Response.send
should receive the resolved value from updateData()
, not the returned value from it since returned value of an async function is a promise object, add missing await will solve the problem:
res.send(await dataService.updateData());
Upvotes: 0
Reputation: 1124
Fix getData
to return Promise, resolved one when success and rejected one when not.
When you have async function it is expected to return promise especially when you want to await
it.
const getData = async () => {
try {
const response = await axios.get<Format>(url);
return Promise.resolve(response.data);
} catch (error) {
console.error(error);
return Promise.reject()
}
};`
Also the updatr data shall resilve promise
const updateData = async (): Promise<Format | undefined> => {
const allData = await getData();
console.log(allData, 'allData in backend');
//edit allData to suitable format here
return Promise.resolve(allData);
};
You need also to wait for the updateData :
import express from 'express';
import dataService from '../services/dataService';
const router = express.Router();
router.get('/', (_req, res) => {
dataService.updateData()
.then(data=>{
res.send(data)
})
.catch(error=>{})
});
export default router;
Upvotes: 1