'dataService'类中的'getData'函数执行对API的GET请求,'updateData'函数中的console.log确实打印了正确的信息,但为'http:// localhost'返回了一个空对象:xxxx / api / data”。我认为这是由于异步问题引起的,但我不知道如何解决它。有什么想法吗?
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);
...
答案 0 :(得分:1)
修复getData
返回Promise,成功则解决一个问题,失败则拒绝一个问题。
当您具有异步功能时,它有望返回诺言,尤其是当您要await
时。
const getData = async () => {
try {
const response = await axios.get<Format>(url);
return Promise.resolve(response.data);
} catch (error) {
console.error(error);
return Promise.reject()
}
};`
更新数据也将重塑承诺
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);
};
您还需要等待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;
答案 1 :(得分:0)
Response.send
应该从updateData()
接收解析的值,而不是从它返回的值,因为异步函数的返回值是一个Promise对象,添加缺少的await将解决问题:
res.send(await dataService.updateData());