在我对前端的响应中结果为空,但在控制台中返回OK



所以,我有一个REST API,我想将一些数据返回到我的前端。

所以我有这个代码:

.then(async result => {
// return result.rows
return result.rows.map(async res1 => {
res1.datasProc = [];
const getDatt = await getDatasProcedimentos(res1.GUIA_SENHA);
res1.datasProc.push(...getDatt);
console.log(res1);
return res1;
})
})

在第2行return result.rows中,可以。但我想用map方法在这个对象上添加一些数据。这些数据来自第6行(SQL查询(。我已经测试了查询函数及其工作情况。在第8行,我的res1对象,包含了我想要的所有数据,但结果为空。

我的控制台.log(res1(

{
NM_PESSOA_FISICA: 'name of someone',
NR_CPF: 'document of someone',
GUIA_SENHA: 'id of company',
PROCEDIMENTO: 'procedure of someone in company',
DATA: 'timestamp',
DS_PROCEDIMENTO: 'description of procedure',
datasProc: [
{ 'timestamp1' },
{ 'timestamp2' },
{ 'timestamp3' }
]
} ... and so on

我对前端的响应(使用端点失眠提示(

result = [
{},
{},
{},
{},
{},
{},
// ... and so on
]

我尝试过其他方法,比如将映射结果分配给变量并返回,但异步块首先返回,然后再返回。

编辑1:我的控制器发送的数据是在一个尝试捕获块:

try {
const guiasPorPeriodo = await guiaDAO.getGuiasPorPeriodo(data_filtro_inicial, data_filtro_final, idClinic);
if (guiasPorPeriodo) {
return res.json({
"resultado": guiasPorPeriodo,
"status": "success",
"message": "enviado com sucesso"
});
} else {
throw new Error('Ocorreu algum erro ao consultar as guias neste período.')
}
} catch (err) {
return res.status(400).json({
"status": "fail",
"error message": `${err.name}: ${err.message}`
});
}

语言:pt-BR-

此语句:

return result.rows.map(async res1 => { 

将返回Promises数组,而不是结果对象。为了确保你的异步函数会返回实际结果的数组,我会尝试这样做:

.then(result => {
// return result.rows
return Promise.all(result.rows.map(async res1 => {
res1.datasProc = [];
const getDatt = await getDatasProcedimentos(res1.GUIA_SENHA);
res1.datasProc.push(...getDatt);
console.log(res1);
return res1;
}))
})

mapper函数被声明为async,因此从技术上讲,它返回一个promise。并且一个未声明为async但返回Promise的函数仍然可以用await调用。

问题在于使用async/await的映射。带有wait的函数将返回一个promise,您需要等待该promise得到解决。试试Promise.all,那应该等到你所有的承诺都得到解决。

.then(async result => {
// return result.rows
return Promise.all(result.rows.map(async res1 => {
res1.datasProc = [];
const getDatt = await getDatasProcedimentos(res1.GUIA_SENHA);
res1.datasProc.push(...getDatt);
console.log(res1);
return res1;
}))
})

另一种方法是使用for循环。使用async/await效果更好。

相关内容

最新更新